Da *_* Li 2 types scala pattern-matching
如何在reflect.runtime.universe.Type上进行模式匹配?
def test(t: reflect.runtime.universe.Type) {
t match {
case Int => \\ ...
case Double => \\ ...
case String => \\ ...
case _ => \\ ...
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为翻译抱怨:
error: pattern type is incompatible with expected type;
found : Int.type
required: reflect.runtime.universe.Type
Note: if you intended to match against the class, try `case _: Int`
case Int => // ...
^
Run Code Online (Sandbox Code Playgroud)
尝试该建议也不起作用:
def test(t: reflect.runtime.universe.Type) {
t match {
case _: Int => \\ ...
case _: Double => \\ ...
case _: String => \\ ...
case _ => \\ ...
}
}
...
error: pattern type is incompatible with expected type;
found : Int
required: reflect.runtime.universe.TypeApi
case _: Int => // ...
^
Run Code Online (Sandbox Code Playgroud)
那么这个的正确语法是什么?
谢谢!
该TypeTagAPI有一个比较操作=:=和获取的方法Type实例给定类,你可以用后卫组合这些来获得期望的结果:
import scala.reflect.runtime.universe._
def test(t: Type) {
t match {
case t if t =:= typeOf[Int] => println("int")
case t if t =:= typeOf[String] => println("string")
case _ =>
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1158 次 |
| 最近记录: |