Why is ClassManifest needed with Array but not List?

前端 未结 4 1433
长情又很酷
长情又很酷 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:32

    The short answer is because that's how the methods are defined in the API:

    def toArray [B >: A] (implicit arg0: ClassManifest[B]) : Array[B]
    def toList : List[A]
    

    If you leave off the :ClassManifest in def test[T:ClassManifest] in your code, then all the compiler knows is that it has some unknown type T and therefore the compiler has no way of finding a ClassManifest for that type.

    Why does the code need a ClassManifest? If you look at the source for toArray you'll see:

    val result = new Array[B](size)
    

    This constructor of Array requires a ClassManifest. See Easy Angel's answer for the documentation of this. Here's an example demonstrating it in the REPL:

    scala> def createArray[T] = new Array[T](10)
    :5: error: cannot find class manifest for element type T
           def createArray[T] = new Array[T](10)
    

    So basically, you have to write T: ClassManifest because Scala needs a ClassManifest in order to create a new array.

提交回复
热议问题