How to find and match parameter datatype at runtime

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.

I think it getting type as Any

use get class and handle type is Any handle it differently using Instanceof

I’m not fluent with the reflection API at all, but I guess it’s because they are different types of types. :wink: #typeSignature gives you a NullaryMethodType while typeOf yields a ClassNoArgsTypeRef. Looks like you can convert the former into the latter via #resultType, which makes the match succeed.

While there certainly are valid uses for this, I’d think they are exceedingly rare. Personally, I’d really make sure that I have exhausted all other approaches for my concrete use case before venturing into reflection.