Manifest vs ClassManifest. What does this Scala error mean?

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 have no clue ...

+3
source share
1 answer

Well, consider a couple of things. At first:

 type T = { def x: Int } 

This type is known as structural. It defines not a class, but a set of objects that share methods with a particular type signature. At runtime, it erases to Object , and any calls to x are made through reflection, since Java has no equivalent.

Further:

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

Note that you did not use new Array , but Array . This is a call to the apply method of a Scala Array . This method requires a ClassManifest implicit parameter that tells Scala how to create an array. This is necessary because arrays are not erased in Java, so Scala must provide the exact type of Java.

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

I am really wondering if it is possible for Scala to use Object here. The ticket may be fine, but do not count on the possibility.

+5
source

All Articles