2
votes

I need to extend a Java class (from a library) of the following type:

public class A<T extends Comparable<? super T>> {
}

I tried to implement the extending Scala class as:

class B[T <: Comparable[_ >: T]] extends A[T] {
}

Unfortunately, this Scala class does not compile with Scala 2.12.1:

Error:(4, 25) illegal cyclic reference involving type T
class B[T <: Comparable[_ >: T]] extends A[T] {

How can I solve this problem?

3

3 Answers

3
votes

You can try defining an alias for this nested type:

object B {
  type ComparableBySuper[LUB] = Comparable[_ >: LUB]
}

class B[T <: ComparableBySuper[T]] extends A[T]
1
votes

This is actually a great usage of what Scala calls type lambdas, which follows roughly the same approach as the accepted answer but sidesteps the requirement of having to nest the type i another object.

The "correct" way to do this with respect to all of Scala's features is:

class B[T <: ({type LUB[A] = Comparable[_ >: A]})#LUB[T]] extends A[T]
0
votes

Scala plugin for IntelliJ IDEA translates this code to

class B[T <: Comparable[(_$1) forSome {type _$1 >: T}]] extends A[T] {
}