Scala 泛型数组
我试图在抽象类中声明一个方法,该方法接收泛型类型 T 的数组。因此:
abstract class Circle[-T] extends Shape[T] {
def draw(points: Array[T]): Unit
}
我遇到的问题是 Scala 编译器抱怨:
逆变类型 T 出现在 Array[T] 类型中的不变位置 价值点
那么,除了以下方法之外,还有什么办法可以解决这个问题吗
def draw[U <: T](points: Array[U]): Unit
请注意,我还需要在 Java 中扩展此类。
I'm trying to declare a method in an abstract class which receives an Array of generic type T. As such:
abstract class Circle[-T] extends Shape[T] {
def draw(points: Array[T]): Unit
}
The problem I'm getting is that Scala compiler complaints with:
contravariant type T occurs in
invariant position in type Array[T] of
value points
So, is there anyway to solve this besides the following?
def draw[U <: T](points: Array[U]): Unit
As a note, I also need to extend this class in Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Scala 的数组直接映射到 Java 数组,并且是不变的(
[T]
而不是[+T]
)数组是一个棘手的野兽。这是在 JVM 上唯一具体化的东西,众所周知,数组方差是被故意破坏的,以便可以实现像 Arrays.sort() 这样的方法。
您可能最好在这里使用“真正的”Java 集合。
回答更一般的问题:是的,如果您想在逆变类的方法中使用参数化不变类型,则必须在该方法的签名中指定上限
Scala's Array maps directly to Java arrays, and is invariant (
[T]
instead of[+T]
)Array is a tricky beast. It's about the only thing that gets reified on the JVM, and it's common knowledge that array variance is purposely broken so that methods like Arrays.sort() could be implemented.
You'd probably be better off using a "true" Java collection here.
To answer the more general question: Yes, if you want to use a parametrised invariant type in a method of a contra-variant class, you have to specify an upper bound in the signature for that method
与此 问题。您可以跳过方差检查
或使用视图绑定
Related to this question. You can either skip check for variance
or use a view bound