均为当前dataType
and typeOf[Int]
打印为Int
但如果你这样做showRaw
你会明白为什么它们不匹配
showRaw(dataType) // NullaryMethodType(TypeRef(ThisType(scala), scala.Int, List()))
showRaw(typeOf[Int]) // TypeRef(ThisType(scala), scala.Int, List())
问题是,只是类型Int
以及返回的 nullary 方法的类型Int
是不同的类型。
尝试添加.resultType
val dataType = getType(thing).decl(TermName("id")).asTerm.typeSignature.resultType
dataType match {
case t if t =:= typeOf[Int] => println("I am Int")
case t if t =:= typeOf[String] => println("String, Do some stuff")
case _ => println("Absurd")
} // I am Int
还值得一提的是.decl(TermName("id"))
返回 getter 符号,它是.decl(TermName("id "))
(带有空格)返回字段符号。因此,您也可以在符号名称中使用空格,而不使用空格.resultType
val dataType = getType(thing).decl(TermName("id ")).asTerm.typeSignature
我将添加到@TomerShetah's answer https://stackoverflow.com/a/65072704/5249621如果目标是“模式匹配”案例类的所有字段,那么这也可以在编译时(大部分)使用无形的 https://github.com/milessabin/shapeless:
import shapeless.Poly1
import shapeless.syntax.std.product._
object printTypes extends Poly1 {
implicit val int: Case.Aux[Int, Unit] = at(t => println(s"I am Int: $t"))
implicit val string: Case.Aux[String, Unit] = at(t => println(s"String, Do some stuff: $t"))
implicit def default[V]: Case.Aux[V, Unit] = at(t => println(s"Absurd: $t"))
}
thing.toHList.map(printTypes)
// I am Int: 1
// String, Do some stuff: Apple
https://scastie.scala-lang.org/DmytroMitin/N4Idk4KcRumQJZE2CHC0yQ https://scastie.scala-lang.org/DmytroMitin/N4Idk4KcRumQJZE2CHC0yQ