我知道isInstanceOf
可用于查找值类型,但如何找到'str'的类型?
它是什么类型的?
scala> val str = ("Scala", "Elixir","Spark")
str: (String, String, String) = (Scala, Elixir, Spark)
以下引发错误(暂时不包括Any / AnyRef等):
scala> str.isInstanceOf[List]
<console>:13: error: type List takes type parameters
str.isInstanceOf[List]
scala> str.isInstanceOf[String]
<console>:13: warning: fruitless type test: a value of type (String, String, String) cannot also be a String (the underlying of String)
str.isInstanceOf[String]
^
res9: Boolean = false
我可以通过这种方式检查,但是有这个名字吗?
scala> str.isInstanceOf[(String, String, String)]
res12: Boolean = true
答案 0 :(得分:3)
在scala repl中使用:type
查找类型
实际类型为Tuple3[String, String, String]
str.isInstanceOf[Tuple3[String, String, String]]
Scala REPL
scala> val str = ("Scala", "Elixir","Spark")
str: (String, String, String) = (Scala,Elixir,Spark)
scala> :type str
(String, String, String)
scala> str.isInstanceOf[Tuple3[String, String, String]]
res2: Boolean = true
scala> str.getClass
res3: Class[_ <: (String, String, String)] = class scala.Tuple3
答案 1 :(得分:2)
如何以编程方式确定val类型?
例如,您想知道值的类型是某些特定类型吗?
resString = """
A₀ = $A0
A₁ = $A1
B₀ = $B0
B₁ = $B1
α = $α
β₁ = $β1
β₂ = $β2
β₃ = $β3
β₄ = $β4
"""
答案 2 :(得分:1)
另一种以编程方式确定类型的方法是使用Manifest:
scala> def getType[T: Manifest](t: T): Manifest[T] = manifest[T]
getType: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]
scala> val str = ("Scala", "Elixir","Spark")
str: (String, String, String) = (Scala,Elixir,Spark)
scala> getType(str)
res0: Manifest[(String, String, String)] = scala.Tuple3[java.lang.String, java.lang.String, java.lang.String]
答案 3 :(得分:0)
现代(意为Scala 2.10或更高版本),Scala以编程方式获取某些内容的编译时类型的方法是使用TypeTag
。
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> def getType[T: TypeTag](value: T) = typeOf[T]
getType: [T](value: T)(implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type
scala> val str = ("Scala", "Elixir","Spark")
str: (String, String, String) = (Scala,Elixir,Spark)
scala> println(getType(str))
(java.lang.String, java.lang.String, java.lang.String)
scala> getType(str) <:< typeOf[(String,String,String)]
res1: Boolean = true
scala> getType((1,2,3)) <:< typeOf[(String,String,String)]
res2: Boolean = false
getClass
将为您提供已擦除的运行时类。 isInstanceOf[T]
将测试擦除的运行时类是否与擦除的运行时类T
的子类相同。
“擦除”表示以下评估为true
。
(1,2,3).isInstanceOf[(String,String,String)]
“运行时”和“编译时间”表示这是true
:
val a: Any = (1,2,3)
a.isInstanceOf[(_,_,_)]
虽然这是false
:
val a: Any = (1,2,3)
getType(a) <:< typeOf[(Int,Int,Int)]
答案 4 :(得分:0)
此方法可以帮助您在运行时获取任何val / var的类型,也可以在已编译的代码中使用。
import scala.reflect.runtime.universe._
def printType[T](x: T)(implicit tag: TypeTag[T]): Unit = println(tag.tpe.toString)
printType(List[Int](1,2,3)) // output: List[Int]
printType(("xxx", 123, 0.1)) // output: (String, Int, Double)
printType(2) // output: Int