Why is ClassManifest needed with Array but not List?

前端 未结 4 1424
长情又很酷
长情又很酷 2020-12-29 09:49

Define the following code:

import scala.collection.JavaConversions._  
val iter:java.util.Iterator[Any] = Array[Any](1, 2, 3).iterator
def func(a:Any):String         


        
4条回答
  •  天涯浪人
    2020-12-29 10:55

    Scala uses JVM native arrays as implementation for Array. Such can only be created with known type.

    Since Sun decided to create legacy artifacts, generic types are erased and no longer present in byte code. That means that at runtime, Array[T] does no longer know the value of T and therefore, the VM can not create the array. There are some more complicated pitfalls you get when you try being compatible to Java 1.4 and introducing generics on array (I don't get the whole depth either), but bottom line is: JVM/Java's arrays are not generic; Scala helps us with the generic abstraction.

    The class manifest you mention is, consequently, essentially a hack. It ensures statically that type information is available when an array is to be created by demanding this implicit parameter. In practice, any method/function that creates an array of a type parameter has to demand an implicit manifest, and all its callees and so on up to the point were the type is known (statically).

提交回复
热议问题