Scala 中泛型类型的模式匹配 [英] Pattern matching on generic type in Scala
问题描述
我有如下所示的 Scala 函数:
I have scala function that looks like this:
现在,取决于 T 的类型(在我的例子中,它可以是 Double
、Boolean
和 LocalDate
),我需要在 ob
上应用函数.像这样的东西(我知道代码没有意义,但我试图传达我的意思):
Now, depending upon the type of T (In my case, it can be Double
, Boolean
and LocalDate
),
I need to apply functions on ob
. Something like this (I know the code will make no sense but I am trying to convey what I mean to do):
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 属性,可以以某种方式使用反射来完成工作吗?甚至有可能吗?
Taking into consideration the Erasure property of Scala, can reflection be somehow used to get the job done? Is it even possible?
推荐答案
如果你使用的是 2.10+,我会选择 TypeTag
I would go with TypeTag if you're on 2.10+
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
另请注意,我只是瞥了一眼 Scala 反射,所以可能有人会写出一个更好的 TypeTag 用法示例.
Note also that I only took a glimpse at scala reflection, so likely somebody may write a better example of TypeTag usage.
这篇关于Scala 中泛型类型的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!