Manifest vs ClassManifest. What does this Scala error mean?
Asked Answered
D

1

3

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 ...

Denunciation answered 14/2, 2011 at 10:45 Comment(2)
Seems like a compiler bug. val a = List[{ def x: Int }](new { def x = 3 }) works ok.Donald
@Eric And there's a difference between a List and an Array, which should be a hint as to what is going on.Necessitous
N
5

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.

Necessitous answered 14/2, 2011 at 13:33 Comment(2)
Is this an example of artefact that would not be there if scala was not JVM language but standalone ?Stringent
@Lukasz It is a limitation imposed by the characteristics of the JVM, though it seems to me that it could be worked around. The way Array works nowadays was introduced with Scala 2.8.0, so this might well be the first time someone tried to do something like that.Necessitous

© 2022 - 2024 — McMap. All rights reserved.