Scala 泛型数组

发布于 2024-09-27 18:48:02 字数 389 浏览 0 评论 0原文

我试图在抽象类中声明一个方法,该方法接收泛型类型 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 技术交流群。

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

发布评论

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

评论(2

猛虎独行 2024-10-04 18:48:02

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

忆离笙 2024-10-04 18:48:02

此 问题。您可以跳过方差检查

scala> import scala.annotation.unchecked.uncheckedVariance
import scala.annotation.unchecked.uncheckedVariance

scala> abstract class Circle[-T] extends Shape[T @uncheckedVariance] {
     |    def draw(points: Array[_<:T]): Unit
     | }
defined class Circle

或使用视图绑定

scala> abstract class Circle[T<%T] extends Shape[T]{
     | def draw(points: Array[_<:T]): Unit
     | }
defined class Circle

Related to this question. You can either skip check for variance

scala> import scala.annotation.unchecked.uncheckedVariance
import scala.annotation.unchecked.uncheckedVariance

scala> abstract class Circle[-T] extends Shape[T @uncheckedVariance] {
     |    def draw(points: Array[_<:T]): Unit
     | }
defined class Circle

or use a view bound

scala> abstract class Circle[T<%T] extends Shape[T]{
     | def draw(points: Array[_<:T]): Unit
     | }
defined class Circle
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文