I hava a Java interface:
public interface FooJava<Element> {
void consume(Element[] elements);
// more methods
}
and I want to implement it in Scala:
// attempt 1
class BarScala[T] extends FooJava[T] {
override def consume(elements: Array[T]): Unit = ???
}
// attempt 2
class BarScala[T <: AnyRef] extends FooJava[T] {
override def consume(elements: Array[T]): Unit = ???
}
In both attempts I get the same compilation error:
class BarScala needs to be abstract, since method consume in trait FooJava of type (elements: Array[T with Object])Unit is not defined
(Note that Array[Element with Object] does not match Array[T]: their type parameters differ)
I don't own the Java class. How can I define my Scala class to avoid this error?
I'm on Scala 2.12
Try
or
The behavior can be reproduced even purely in Scala. Although for
T <: Upper,T with Upper =:= T, we can't replaceT with Upperwith justTin overriding methodSimilarly,
Probably the thing is that for
T <: Upper,T with Upper <: TandT <: T with Upperhttps://scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
but not
T with Upper ≡ Thttps://scala-lang.org/files/archive/spec/2.13/03-types.html#equivalence
This behavior is changed in Scala 3 https://scastie.scala-lang.org/DmytroMitin/LHhlufv8ReqoN6w2ZL0BLQ/1