Manifest vs ClassManifest. What does this Scala error mean?

为君一笑 提交于 2020-01-04 02:54:54

问题


What does this error mean?

scala> val a = Array[{ def x: Int }](new { def x = 3 }) 
<console>:5: error: type mismatch;
 found   : scala.reflect.Manifest[java.lang.Object]
 required: scala.reflect.ClassManifest[AnyRef{def x: Int}]
       val a = Array[{ def x: Int }](new { def x = 3 })
                                    ^

I don't have a clue ...


回答1:


Ok, let's consider a couple of things. First:

type T = { def x: Int }

This type is known as a structural type. It defines not a class, but a set of objects that share methods with a certain type signature. At run-time, it is erased to Object, and any calls to x are done through reflection, since Java doesn't have any equivalent to it.

Next:

val a = Array[{ def x: Int }](new { def x = 3 }) 

Note that you did not use new Array, but Array. That is a call to the apply method of Scala's Array object. This method requires a ClassManifest implicit parameter that will tell Scala how to create the array. This is necessary because arrays are not erased in Java, so Scala has to provide the precise type to Java.

And here's the problem: there's no such type in Java.

I do wonder if it wouldn't be possible for Scala to use Object here. A ticket might be in order, but don't count on it being possible.



来源:https://stackoverflow.com/questions/4991215/manifest-vs-classmanifest-what-does-this-scala-error-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!