开发者

What is the Scala equivalent of C++ typeid?

开发者 https://www.devze.com 2023-03-30 01:40 出处:网络
For example, if I do scala> val a = Set(1,2,3) a: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

For example, if I do

scala> val a = Set(1,2,3)
a: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

in the REPL, I want to see the most refined type of "a" in order to 开发者_StackOverflow中文版know whether it's really a HashSet. In C++, typeid(a).name() would do it. What is the Scala equivalent?


scala> val a = Set(1,2,3)
a: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> a.getClass.getName
res0: java.lang.String = scala.collection.immutable.Set$Set3

(Yes, it really is an instance of an inner class called Set3--it's a set specialized for 3 elements. If you make it a little larger, it'll be a HashTrieSet.)

Edit: @pst also pointed out that the type information [Int] was erased; this is how JVM generics work. However, the REPL keeps track since the compiler still knows the type. If you want to get the type that the compiler knows, you can

def manifester[A: ClassManifest](a: A) = implicitly[ClassManifest[A]]

and then you'll get something whose toString is the same as what the REPL reports. Between the two of these, you'll get as much type information as there is to be had. Of course, since the REPL already does this for you, you normally don't need to use this. But if for some reason you want to, the erased types are available from .typeArguments from the manifest.

0

精彩评论

暂无评论...
验证码 换一张
取 消