Scala中泛型类型的模式匹配

时间:2014-01-22 14:10:50

标签: scala generics reflection pattern-matching erasure

我有scala函数,如下所示:

现在,根据T的类型(在我的情况下,它可以是DoubleBooleanLocalDate), 我需要在ob上应用函数。这样的事情(我知道代码没有意义,但我想传达我的意思):

def X[T](ob: Observable[T]): Observable[T] = {
    //code  
    T match {
    case Double => DoSomething1(ob:Observable[Double]):Observable[Double]
    case Boolean => DoSomething2(ob:Observable[Boolean]):Observable[Boolean]
    case LocalDate => DoSomething3(ob:Observable[LocalDate]):Observable[LocalDate]
    }
}

考虑到Scala的Erasure属性,可以用某种方式反射来完成工作吗?它甚至可能吗?

1 个答案:

答案 0 :(得分:22)

如果你在2.10 +

,我会选择TypeTag
import reflect.runtime.universe._

class Observable[Foo]

def X[T: TypeTag](ob: Observable[T]) = ob match {
    case x if typeOf[T] <:< typeOf[Double]   => println("Double obs")
    case x if typeOf[T] <:< typeOf[Boolean]  => println("Boolean obs")
    case x if typeOf[T] <:< typeOf[Int]      => println("Int obs")
}

X(new Observable[Int])
// Int obs

另见this lengthy, but awesome answer

另请注意,我只是瞥了一眼scala反射,所以有人可能会写一个更好的TypeTag用法示例。

相关问题