Cor*_*ped 20 generics reflection scala pattern-matching erasure
我有scala函数,如下所示:
现在,根据T的类型(在我的情况下,它可以是Double,Boolean和LocalDate),我需要应用函数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]
}
}
Run Code Online (Sandbox Code Playgroud)
考虑到Scala的Erasure属性,可以用某种方式反射来完成工作吗?它甚至可能吗?
om-*_*nom 23
如果您使用的是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
Run Code Online (Sandbox Code Playgroud)
另请注意,我只是瞥了一眼scala反射,所以有人可能会写一个更好的TypeTag用法示例.
| 归档时间: |
|
| 查看次数: |
10968 次 |
| 最近记录: |