加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala – 返回一个类型

发布时间:2020-12-16 18:03:56 所属栏目:安全 来源:网络整理
导读:我想从函数中返回一个类型.例如: class Supercase class One(a: Int) extends Supercase class Two(b: Float) extends Supercase class Unknown extends Superdef decide(criterion: String): ??? = { criterion match { case "one" = One case "two" = Two
我想从函数中返回一个类型.例如:

class Super
case class One(a: Int) extends Super
case class Two(b: Float) extends Super
case class Unknown extends Super

def decide(criterion: String): ??? = {
  criterion match {
    case "one" => One
    case "two" => Two
    case _ => Unknown
  }
}

所以我想返回类型本身,将它存储在Map中,以便我可以在以后的某个地方应用它:

val test = Buffer(
  ("ahaha" -> "one")
  ("ohoho" -> "two")
  ("lalala" -> "one")
)

var map = scala.collection.mutable.Map[String,Super]()

test.map {pair =>
  map(pair._1) = decide(pair._2)
}

以后我可以这样说:

def act(code: String) {
  map(code) match {
    case One => doSmth[One]()
    case Two => doSmth[Two]()
    case _ => doNothing()
  }
}

我知道有些部分,比如case类的未使用的参数在这里可能看起来很奇怪,但这就是我在工作的环境中的情况,这个例子是完整的,因为我不确定它是否会有所不同,如果我拿走一些东西……

那么如何让决定函数返回一个类型,然后以类似于我所展示的方式使用它?

解决方法

我认为您可能需要案例对象One等,而不是使用Class或ClassTag.然后你得到有用的匹配支持.对于act方法,你的case对象可以返回ClassTag或类似的东西,或者只是让one与doSmth [OneClass]等关联.

看来你可以将你的案例伴侣变成case对象.不是那么特别.

package typeswitch
import reflect.runtime.universe._

sealed trait Selection

class Super
case class One(a: Int) extends Super
case object One extends Selection
case class Two(b: Float) extends Super
case object Two extends Selection
case class Unknown() extends Super
case object Unknown extends Selection

object Test extends App {
  type What = Selection

  def decide(criterion: String): What = criterion match {
    case "one" => One
    case "two" => Two
    case _ => Unknown
  }

  val test = List(
    "ahaha" -> "one","ohoho" -> "two","lalala" -> "one"
  )

  val m = scala.collection.mutable.Map[String,What]()

  test map (pair => m(pair._1) = decide(pair._2))

  def act(code: String) = m(code) match {
    case One => doSmth[One]()
    // non-exhaustive
    //case Two => doSmth[Two]()
    case Unknown => doNothing()
    // handle exhaustively
    case s: Selection => doSmthNew(s)
  }
  def doSmthElse[A <: Super]()(implicit t: TypeTag[A]): A = {
    Console println s"Do st with $t"
    val claas: Class[_] = t.mirror.runtimeClass(t.tpe)
    null.asInstanceOf[A]
  }
  def doSmth[A <: Super]()(implicit t: ClassTag[A]): A = {
    Console println s"Do st with $t"
    val claas: Class[_] = t.runtimeClass
    null.asInstanceOf[A]
  }
  def doSmthNew[A >: What : ClassTag,B <: Super](what: A): B = {
    Console println s"Do st new with $what"
    null.asInstanceOf[B]
  }
  def doNothing() { }

  val res = act("lalala")
  Console println s"Got $res?"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读