如何使用“匹配”语句来识别类变量的值?以下是无效的,我无法找到一个可接受的变种 - 比如果其他...否则,如果...否则...如何在Scala“匹配”语句中匹配类?
val c: Class[_] = classOf[Int]
val what = c match { case classOf[Int] => "int!"; case classOf[Float] => "float!" }
编译器会抱怨:error: not found: type classOf
,当然还有,我不能使用Class[Int]
,因为这种类型的信息将被删除:
c match { case Class[Int] => "int!"; case Class[Float] => "float!" }
error: type Class of type Class does not take type parameters.
我也试着像变种Int.class
,都无济于事。 (我并不想转换为字符串:我觉得让编译器捕获重命名/移动类是很重要的。)
我是密集的,还是我偶然发现了一个Scala盲点?
好了,下面的答案的答案正确的(和感谢! ),但它越来越显得这是Scala中的一种丑陋的洞。类是单身人士,所以你没有理由必须将它们分配给变量以便高效地匹配它们 - 也不要诉诸使用级联的ifs,写成守卫或单独的语句。但显然是这样。 – Tim