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

In REPL, there is a command to print 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 :: expr function in my Scala type printing program?

Let me explain the functionality of “: type expr”, which 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 of REPL (where I don't have a command :type )?

+4
source share
4 answers

The following implicit conversion should do the trick for you:

 import reflect.runtime.universe._ implicit class ColonTypeExtender [T : TypeTag] (x : T) { def colonType = typeOf[T].toString } 
+3
source

I looked at the sources of REPL (or better scalac, which contains REPL) and found this ( Source ):

 private def replInfo(sym: Symbol) = { sym.info match { case NullaryMethodType(restpe) if sym.isAccessor => restpe case info => info } } 

The info method scala.reflect.internal.Symbols.Symbol returns Type ( Source ). Later, toString is called for this type, so you must do the same if you want information about the same type:

 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 
+7
source

Is that what you would like to achieve?

 val s = "House" println(s.getClass.getName) // java.lang.String println(s.getClass.getSimpleName) // String 
+1
source

Tested with Scala REPL 2.11:

Add _ after the function name to treat it as a partially applied function.

Example:

 scala> def addWithSyntaxSugar(x: Int) = (y:Int) => x + y addWithSyntaxSugar: (x: Int)Int => Int scala> addWithSyntaxSugar _ res0: Int => (Int => Int) = <function1> scala> 
0
source

All Articles