Scala 程序中的推断类型 [英] Inferred type in a Scala program
本文介绍了Scala 程序中的推断类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Scala REPL 显示了表达式的推断类型.有没有办法知道普通 Scala 程序中的推断类型?
The Scala REPL shows the inferred type of an expression. Is there a way to know the inferred type in a normal Scala program ?
例如,
val x = {
//some Scala expressions
}
现在我想知道 x 的实际类型.
Now I want to know the actual type of x.
推荐答案
也许 TypeTag 是您要找的吗?
Perhaps TypeTag is what you are looking for?
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> def typeOf[T](x:T)( implicit tag: TypeTag[T] ) = tag
typeOf: [T](x: T)(implicit tag: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]
scala> class Foo( a:Int )
defined class Foo
scala> trait Bar
defined trait Bar
scala> val x = new Foo(3) with Bar
x: Foo with Bar = $anon$1@62fb343d
scala> val t = typeOf(x)
t: reflect.runtime.universe.TypeTag[Foo with Bar] = TypeTag[Foo with Bar]
scala> t.tpe
res20: reflect.runtime.universe.Type = Foo with Bar
scala> t.tpe.toString
res21: String = Foo with Bar
并且只是为了证明它产生表达式的静态类型而不是对象的动态类型:
And just to demonstrate that it yields the static type of the expression rather than the dynamic type of the object:
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)
scala> val s:Seq[Int] = l
s: Seq[Int] = List(1, 2, 3)
scala> typeOf(s)
res22: reflect.runtime.universe.TypeTag[Seq[Int]] = TypeTag[scala.Seq[Int]]
这篇关于Scala 程序中的推断类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文