3

I have just begun investigating Scala and found the following perplexing quote in the Wikipedia page on Scala:

[Scala] cleans up [...] poor design decisions in Java (e.g. type erasure...

I thought type erasure was a limitation imposed by the Java Virtual Machine, so given that the JVM executes Scala code, how has this been "cleaned up"?

I do appreciate that the designer of Scala also contributed to the JVM, so I am curious to understand if he / the Scala team has augmented the Scala compiler to carry rich run-time type information and thus 'clean up' type erasure. Is this the case?

Thanks in advance for any insight you can provide.

4

2 回答 2

4

不幸的是,Scala 仍然必须在 JVM 中处理运行时的类型擦除。然而,一些关于泛型的事情已经被清理了:

  • 类型参数是非可选的(没有List,只有List<String>/ List[String]
  • 协变/逆变的语言支持

此外,为了处理 JVM TypeTags(在 2.9 中Manifests)的限制,可用于存储类型信息,否则这些信息会在运行时丢失。例如:

import scala.reflect.runtime.universe._

def foo[T : TypeTag](x: List[T]) = {
  println(implicitly[TypeTag[T]].tpe)
}

这将打印列表元素的类型。如果 - 例如 - 您传递一个空列表,则某些东西将不可恢复地丢失:

foo(List.empty[String])
// not distinguishable without TypeTags from
foo(List.empty[Int])
于 2013-06-06T22:49:29.447 回答
1

好吧,这句话说的是“清理”,而不是“消除”。类型擦除仍然存在,它可以咬你。

Scala 有Manifests。Manifest是一个包含有关您的实际类型的信息的对象。这是关于s 的一个很好的答案。Manifest

于 2013-06-06T22:46:21.223 回答