Scala shared array

I am trying to declare a method in an abstract class that receives an array of type T. As such:

abstract class Circle[-T] extends Shape[T] {
   def draw(points: Array[T]): Unit
}

The problem I am getting is that the Scala compiler complains with:

contravariant type T occurs in an invariant position in type Array [T] of value

So, is there a way to solve this other than the following?

def draw[U <: T](points: Array[U]): Unit

As a side note, I also need to extend this class in Java.

+3
source share
2 answers

Scala Array maps directly to Java arrays and is invariant ( [T]instead [+T])

- . , JVM, , , , Arrays.sort().

, "" Java .

: , ,

+4

.

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
+3

Source: https://habr.com/ru/post/1769741/


All Articles