scalatype-inferenceread-eval-print-loop

Inferred type in a Scala program


The Scala REPL shows the inferred type of an expression. Is there a way to know the inferred type in a normal Scala program ?

For example,

val x = {
//some Scala expressions
}

Now I want to know the actual type of x.


Solution

  • Perhaps TypeTag is what you are looking for?

    scala> import scala.reflect.runtime.universe._
    import scala.reflect.runtime.universe._
    
    scala> def typeOf[T](x:T)( implicit tag: TypeTag[T] ) = tag
    typeOf: [T](x: T)(implicit tag: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]
    
    scala> class Foo( a:Int )
    defined class Foo
    
    scala> trait Bar
    defined trait Bar
    
    scala> val x = new Foo(3) with Bar
    x: Foo with Bar = $anon$1@62fb343d
    
    scala> val t = typeOf(x)
    t: reflect.runtime.universe.TypeTag[Foo with Bar] = TypeTag[Foo with Bar]
    
    scala> t.tpe
    res20: reflect.runtime.universe.Type = Foo with Bar
    
    scala> t.tpe.toString
    res21: String = Foo with Bar
    

    And just to demonstrate that it yields the static type of the expression rather than the dynamic type of the object:

    scala> val l = List(1,2,3)
    l: List[Int] = List(1, 2, 3)
    
    scala> val s:Seq[Int] = l
    s: Seq[Int] = List(1, 2, 3)
    
    scala> typeOf(s)
    res22: reflect.runtime.universe.TypeTag[Seq[Int]] = TypeTag[scala.Seq[Int]]