我想从函数返回一个类型。例如:
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()
}
}
我知道有些部分,比如案例类未使用的参数,在这里可能看起来很奇怪,但这就是我正在工作的环境中的情况,这个例子是如此完整,因为我不确定它是否会如果我拿走一些东西就会有所不同......
那么如何让 decide
函数返回一个类型,然后以类似于我所展示的方式使用它?
最佳答案
我认为您可能需要case object One
等,而不是使用Class或ClassTag。然后您将获得有用的比赛支持。对于 act
方法,您的 case 对象可以返回 ClassTag 或类似的,或者只是让 act 将 One 与 doSmth[OneClass] 等关联起来。
看来你可以将你的案例同伴变成案例对象。是不是很特别。
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?"
}
关于Scala - 返回一个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13805612/