清单与类清单.这个Scala错误是什么意思? [英] Manifest vs ClassManifest. What does this Scala error mean?

查看:70
本文介绍了清单与类清单.这个Scala错误是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此错误是什么意思?

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 })
                                    ^

我没有头绪...

推荐答案

好,让我们考虑几件事.首先:

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

type T = { def x: Int }

这种类型称为结构类型.它不定义类,而是定义一组共享具有特定类型签名的方法的对象.在运行时,它会被擦除为Object,对x的任何调用都是通过反射完成的,因为Java没有与此等效的东西.

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.

下一步:

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

请注意,您没有使用new Array,而是使用了Array.那是对Scala Array对象的apply方法的调用.该方法需要一个ClassManifest隐式参数,该参数将告诉Scala如何创建数组.这是必需的,因为在Java中不会删除数组,因此Scala必须为Java提供精确的类型.

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.

这是问题所在:Java中没有这样的类型.

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

我确实想知道Scala是否不可能在这里使用Object.可能有票证,但不要指望有可能.

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.

这篇关于清单与类清单.这个Scala错误是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆