How to find class parameter datatype at runtime in scala

后端 未结 2 601
谎友^
谎友^ 2021-01-27 23:40
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:          


        
2条回答
  •  悲哀的现实
    2021-01-28 00:06

    Both current dataType and typeOf[Int] are printed as Int but if you do showRaw you'll see why they don't match

    showRaw(dataType) // NullaryMethodType(TypeRef(ThisType(scala), scala.Int, List()))
    showRaw(typeOf[Int]) // TypeRef(ThisType(scala), scala.Int, List())
    

    The thing is that just the type Int and the type of nullary method returning Int are different types.

    Try to add .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
    

    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

    val dataType = getType(thing).decl(TermName("id ")).asTerm.typeSignature
    

    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:

    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

提交回复
热议问题