如何匹配 Scala 中的类“匹配"?陈述? [英] How can I match classes in a Scala "match" statement?
问题描述
如何使用匹配"语句来识别类变量的值?以下是无效的,我找不到可接受的变体——除了 if ... else if ... else ...
How can I use a "match" statement to identify the value of a class variable? The following is invalid, and I can't find an acceptable variant -- other than if ... else if ... else ...
val c: Class[_] = classOf[Int]
val what = c match { case classOf[Int] => "int!"; case classOf[Float] => "float!" }
编译器抱怨:error: not found: type classOf
当然,我不能使用 Class[Int]
因为该类型信息已被删除:
And of course, I can't use Class[Int]
because that type information is erased:
c match { case Class[Int] => "int!"; case Class[Float] => "float!" }
error: type Class of type Class does not take type parameters.
我也尝试过像 Int.class
这样的变体,但都无济于事.(而且我真的不想转换为字符串:我觉得让编译器捕获重命名/移动类很重要.)
I've also tried variants like Int.class
, all to no avail. (And I don't really want to convert to strings: I feel it's important to have the compiler catch renamed/moved classes.)
我是不是太笨了,还是偶然发现了 Scala 盲点?
Am I being dense, or have I stumbled into a Scala blind spot?
推荐答案
如果为类值创建稳定的标识符(即 val),则可以匹配它们,
You can match on class values if you create a stable identifier (ie. a val) for them,
scala> val c: Class[_] = classOf[Int]
c: Class[_] = int
scala> val ClassOfInt = classOf[Int]
ClassOfInt: java.lang.Class[Int] = int
scala> val ClassOfFloat = classOf[Float]
ClassOfFloat: java.lang.Class[Float] = float
scala> val what = c match {
| case ClassOfInt => "int!"
| case ClassOfFloat => "float!"
| }
what: String = int!
请注意,您不能匹配类型(即 Class[Int]),因为擦除意味着 Class[T] 的不同类型实例化在运行时无法区分......因此下面的警告
Note that you can't match on type (ie. Class[Int]) because erasure means that the different type instantiations of Class[T] are indistinguishable at runtime ... hence the warning below
scala> val what = c match {
| case _: Class[Int] => "int!"
| case _: Class[Float] => "float!"
| }
warning: there were 2 unchecked warnings; re-run with -unchecked for details
what: java.lang.String = int!
这篇关于如何匹配 Scala 中的类“匹配"?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!