如何在我的 Scala 程序中获得 Scala REPL 的功能:type 命令 [英] How can I get the functionality of the Scala REPL :type command in my Scala program
本文介绍了如何在我的 Scala 程序中获得 Scala REPL 的功能:type 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 REPL 中有一个打印类型的命令:
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
如何在我的 Scala 程序中使用:type expr"功能来打印类型?
How can I get this ":type expr" functionality in my Scala program to print types?
让我澄清一下我想要的 ":type expr" 功能,像这样:
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
如何在 REPL 之外的 Scala 程序中获得这样的colonType
"方法(我没有可用的 :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)?
推荐答案
以下隐式转换应该可以为您解决问题:
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
}
这篇关于如何在我的 Scala 程序中获得 Scala REPL 的功能:type 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文