0

In Java we can do switch(value) {case(x): // do something;}

In Scala, we can do something similar with case match expressions:

val a = 1
a match {
  case 1 => 1
  case 2 => 2
} // 1

However, it doesn't work with a value of type 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
            ^

Instead, I have to do this:

if (tpe =:= typeOf[Int]) {...}
else if (tpe =:= Option[Any]) {...}

Is there a chance to use case match expression here?

yiksanchan
  • 1,890
  • 1
  • 13
  • 37

1 Answers1

0

You can do this (although I'm not sure why you'd want to):

val tpe = typeOf[Int]

val intType = typeOf[Int]
val optionAnyType = typeOf[Option[Any]]

tpe match {
    case `intType` => 1
    case `optionAnyType` => 2
} //1
Lasf
  • 2,536
  • 1
  • 16
  • 35
  • What if I want to "range match"? e.g., ```if (tpe <:< typeOf[Seq[Any]]) {...} else if (tpe <:< Option[Any]) {...} else {...}``` – yiksanchan Sep 21 '18 at 22:20
  • @YikSanChan Then you'd need to do this: `tpe match { case i if i <:< typeOf[Seq[Any]] => ...; case j if j <:< typeOf[Option[Any]] => ...; case _ => ... }` – Lasf Sep 23 '18 at 09:40