大小写匹配 `reflect.runtime.universe.Type`
case match a `reflect.runtime.universe.Type`
在Java中我们可以做到switch(value) {case(x): // do something;}
在 Scala 中,我们可以用大小写匹配表达式做类似的事情:
val a = 1
a match {
case 1 => 1
case 2 => 2
} // 1
但是,它不适用于 reflect.runtime.universe.Type
类型的值。
val tpe = typeOf[Int]
tpe match {
case typeOf[Int] => 1
case typeOf[Option[Any]] => 2
}
error: not found: type typeOf
case typeOf[Int] => 1
^
相反,我必须这样做:
if (tpe =:= typeOf[Int]) {...}
else if (tpe =:= Option[Any]) {...}
这里有机会使用大小写匹配表达式吗?
你可以这样做(虽然我不确定你为什么想要这样做):
val tpe = typeOf[Int]
val intType = typeOf[Int]
val optionAnyType = typeOf[Option[Any]]
tpe match {
case `intType` => 1
case `optionAnyType` => 2
} //1
在Java中我们可以做到switch(value) {case(x): // do something;}
在 Scala 中,我们可以用大小写匹配表达式做类似的事情:
val a = 1
a match {
case 1 => 1
case 2 => 2
} // 1
但是,它不适用于 reflect.runtime.universe.Type
类型的值。
val tpe = typeOf[Int]
tpe match {
case typeOf[Int] => 1
case typeOf[Option[Any]] => 2
}
error: not found: type typeOf
case typeOf[Int] => 1
^
相反,我必须这样做:
if (tpe =:= typeOf[Int]) {...}
else if (tpe =:= Option[Any]) {...}
这里有机会使用大小写匹配表达式吗?
你可以这样做(虽然我不确定你为什么想要这样做):
val tpe = typeOf[Int]
val intType = typeOf[Int]
val optionAnyType = typeOf[Option[Any]]
tpe match {
case `intType` => 1
case `optionAnyType` => 2
} //1