How can I get the functionality of the Scala REPL

2020-02-29 06:34发布

问题:

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

回答1:

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
}


回答2:

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


回答3:

Is that what you'd like to achieve?

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


回答4:

Tested with Scala REPL 2.11 :

Add _ after function name to treat it as 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> 


标签: scala