Scala 中泛型类型的模式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21285235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:01:23  来源:igfitidea点击:

Pattern matching on generic type in Scala

scalagenericsreflectionpattern-matchingerasure

提问by Core_Dumped

I have scala function that looks like this:

我有如下所示的 Scala 函数:

Now, depending upon the type of T (In my case, it can be Double, Booleanand 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):

现在,根据 T 的类型(在我的情况下,它可以是Double,BooleanLocalDate),我需要在 上应用函数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]
    }
}

Taking into consideration the Erasure property of Scala, can reflection be somehow used to get the job done? Is it even possible?

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

回答by om-nom-nom

I would go with TypeTag if you're on 2.10+

如果您使用的是 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

See also this lengthy, but awesome answer

另请参阅这个冗长但很棒的答案

Note also that I only took a glimpse at scala reflection, so likely somebody may write a better example of TypeTag usage.

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