Convert signature `` `` `` `s``? super T` to Scala (generics)

Problem:

Considering this issue of porting a Java signature

public <A extends Comparable<? super A>> void sort(List<A> list) { } 

before Scala, there seems to be no way to escape

illegal cyclic reference involving type T

if you are doing a literal translation like this.

 def compilerFailure[T <: Comparable[_ >: T]](a: Array[T]): T = { } 

The workaround seems to be to do this instead

 def workaround[A <: Comparable[U], U >: A](list: List[A]) { } 

which, if you go from the byte code back to Java, you get this (which loses the super part)

 public <T extends Comparable<U>, U> void scalaToJava(List<U> a) { } 

My questions:

Is the version of scalaToJava equivalent to the following:

 public <T extends Comparable<?>> void sort(List<T> a) { 

I realized when U unlimited, can it be the same ? or Object no? Then, if this is the case, is a version of Scala workaround equivalent to

 def sort[A <: Comparable[_]](list: List[A]) { } 

All of them seem to be compiled for my use case (as for placing different subtypes in the collection and the possibility of sorting them). NB. I'm curious about what mechanics are and what causes a cyclic link error, and I understand that Scala offers the best alternatives in terms of covariance, etc. (i.e., Ordering ).

+4
source share
1 answer
 public <T extends Comparable<?>> void sort(List<T> a) 

too general, because then you could, for example, go to List<A> extends Comparable<Int> , where the comparison function is not applicable to values โ€‹โ€‹of type List<A> .

You were on the right track with your workaround, but made a small mistake. It should be:

 def workaround[A <: Comparable[A], U >: A](list: List[U]) { } 

But note that this is not how Scala usually resolves this situation:

See scala.math.Ordering .

+4
source

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


All Articles