import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._
def getType[T: TypeTag](obj: T) = typeOf[T]
case class Thing(
val id: Int,
var name: String
)
val thing = Thing(1, "Apple")
val dataType = getType(thing).decl(TermName("id")).asTerm.typeSignature
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")
}
Not able to digest why result is Absurd
instead of I am int
?
My aim is to know data-type of class parameter at runtime and match it to predefined types.
Both current
dataType
andtypeOf[Int]
are printed asInt
but if you doshowRaw
you'll see why they don't matchThe thing is that just the type
Int
and the type of nullary method returningInt
are different types.Try to add
.resultType
It's also worth mentioning that
.decl(TermName("id"))
returns getter symbol, it's.decl(TermName("id "))
(with a blank space) that returns field symbol. So alternatively you can do with a blank space in the symbol name and without.resultType
I'll add to @TomerShetah's answer that if the goal is "pattern matching" all fields of a case class then this can be done also at compile time (mostly) with Shapeless:
https://scastie.scala-lang.org/DmytroMitin/N4Idk4KcRumQJZE2CHC0yQ