In the REPL there's a command to print the type:
scala> val s = "House"
scala> import scala.reflect.runtime.universe._
scala> val li = typeOf[List[Int]]
scala> :type s
String
scala> :type li
reflect.runtime.universe.Type
How can I get this ":type expr" functionality in my Scala program to print types?
Let me clarify the ":type expr" functionality I would like to have, something like this:
println(s.colonType) // String
println(li.colonType) // reflect.runtime.universe.Type
How can I get such a "colonType
" method in my Scala program outside the REPL (where I don't have the :type
command available)?
I looked into the sources of the REPL (or better of scalac which contains the REPL) and found this (Source):
private def replInfo(sym: Symbol) = {
sym.info match {
case NullaryMethodType(restpe) if sym.isAccessor => restpe
case info => info
}
}
Method info
of scala.reflect.internal.Symbols.Symbol
returns a Type
(Source). Later toString
is called on this type, therefore you should do the same if you want the same type information:
scala> import scala.reflect.runtime.{universe => u}
import scala.reflect.runtime.{universe=>u}
scala> u.typeOf[List[String]].toString
res26: String = scala.List[String]
scala> u.typeOf[Int => String].toString
res27: String = Int => String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With