清单与类清单。这个 Scala 错误是什么意思?

发布于 2024-10-17 05:01:22 字数 365 浏览 7 评论 0原文

这个错误是什么意思?

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

我不知道...

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭泣的笑容 2024-10-24 05:01:22

好吧,让我们考虑几件事。第一:

type T = { def x: Int }

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

接下来:

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

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

问题是:Java 中没有这样的类型。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文