【发布时间】:2015-04-02 19:38:42
【问题描述】:
如何对 reflect.runtime.universe.Type 进行模式匹配?
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.type
required: reflect.runtime.universe.Type
Note: if you intended to match against the class, try `case _: Int`
case Int => // ...
^
尝试该建议也不起作用:
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 => // ...
^
那么正确的语法是什么?
谢谢!
【问题讨论】:
-
ps.: 使用 if 语句,我可以执行以下操作: if (t==reflect.runtime.universe.typeOf[String]) // ... 但是,这不是在模式匹配语法中工作: t match { case reflect.runtime.universe.typeOf[String] => \\ ... case _ => } 我得到提示错误:类型 typeOf 不是 scala.reflect 的成员。 api.JavaUniverse case reflect.runtime.universe.typeOf[String] => fieldMap(pName).set(pVal)
-
还有一个问题:做if语句我发现scala.Int显然和Int不一样。但是,reflect.runtime.universe.typeOf[scala.Int]) 的结果是 Int,(t==reflect.runtime.universe.typeOf[Int]) 的结果和 if ( t==reflect.runtime.universe.typeOf[scala.Int])。如何解决?
-
如果不使用
if,你需要一个稳定的模式匹配标识符,并且你想使用=:=而不是==。试试case t if t =:= typeOf[String] => ... -
模式匹配不是一个好主意:groups.google.com/d/msg/scala-internals/P2_okWT4muw/…。所以,按照@lmm 的建议,使用
if语句和=:=。
标签: scala types pattern-matching