Generics: Type argument is not within its bounds

Hi,

So I’d like to sort a list of elements according to the natural order, where each element type (Int, Long, etc) should implement a Comparable interface:

fun <T : Comparable<T>> naturalSort(list: List<T>): List<T> {
    val natComparator = naturalOrder<T>() // results in the compiler error: "Type argument is not within its bounds: should be subtype of 'Comparable<T>'"
    return list.sortedWith(natComparator)
}

But the second line result in the compiler error (see above). Why? As I see it, T has been defined as <T : Comparable<T>>, that is T is a subtype of Comparable<T>.

Any ideas? Thanks

1 Like

Well, your code snipped works for me (tested with kotlin 1.3.41-1 in repl).
What is your Kotlin version?

import kotlin.reflect.KProperty
import org.junit.Assert.assertTrue
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.junit.Test
...
fun <T : kotlin.Comparable<T>> naturalSort(list: List<T>): List<T> {
    val natComparator = naturalOrder<T>() // results in the compiler error: "Type argument is not within its bounds: should be subtype of 'Comparable<T>'"
    return list.sortedWith(natComparator)
}

It works for me too providing I explicitly specify that kotlin.Comparable (see above) should be used. If I just use Comparable it looks like java.lang.Comparable is used and I’m getting the compiler error. My imports are not excessive, really not sure why kotlin compiler defaults to java.lang.Comparable in this case.

Any ideas? Thanks

Your suspicion seems to be true. However, it is very strange that Java Comparable is used instead of the native one.

What happens if you import kotlin.Comparator

Importing kotlin.Comparable (and kotlin.Comparator) doesn’t help, still getting the same error.

Your code works fine for me. Maybe try updating to the latest kotlin version.
Also what version are you using? Can you create a standalone project to recreate the error? Either way if you are on the latest version (1.3.41 I believe) you should create an issue here.

I’m running kotlin 1.3.41 in a Kotlin + Gradle + Eclipse project. Eclipse highlights this error when editing the file and gradle build fails with the same error if the project is built outside of Eclipse.