Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the functionality of the Scala REPL :type command in my Scala program

Tags:

scala

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)?

like image 460
user1525911 Avatar asked Dec 21 '22 19:12

user1525911


1 Answers

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
like image 144
kiritsuku Avatar answered Jan 17 '23 13:01

kiritsuku