【问题标题】:case match a `reflect.runtime.universe.Type` [duplicate]大小写匹配`reflect.runtime.universe.Type` [重复]
【发布时间】:2018-09-22 05:37:29
【问题描述】:

在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]) {...}

这里有机会使用大小写匹配表达式吗?

【问题讨论】:

    标签: scala scala-reflect


    【解决方案1】:

    你可以这样做(虽然我不确定你为什么要这样做):

    val tpe = typeOf[Int]
    
    val intType = typeOf[Int]
    val optionAnyType = typeOf[Option[Any]]
    
    tpe match {
        case `intType` => 1
        case `optionAnyType` => 2
    } //1
    

    【讨论】:

    • 如果我想“范围匹配”怎么办?例如,if (tpe <:< typeOf[Seq[Any]]) {...} else if (tpe <:< Option[Any]) {...} else {...}
    • @YikSanChan 那么你需要这样做:tpe match { case i if i <:< typeOf[Seq[Any]] => ...; case j if j <:< typeOf[Option[Any]] => ...; case _ => ... }
    猜你喜欢
    • 2012-12-03
    • 2015-03-17
    • 2021-07-14
    • 1970-01-01
    • 2015-04-02
    • 2014-08-05
    • 1970-01-01
    • 2020-09-11
    • 2021-12-21
    相关资源
    最近更新 更多