Using generic class in kotlin


#1

Why doesn’t this work ?

class MergeSort<T : Comparable<Any>>
{
     ...
}

fun main(args : Array<String>)
{
    val arr = arrayOf(5, 3, 2, 1, 4, 6, 7)

    println("before sort")
    for (i in arr)
        print(i.toString() + ", ")
    println()

    val mergesort = MergeSort<Int>() //Type arguement is not within its bounds. Expected : Comparable<Any> Found : Int
    mergesort.sort(arr)

    println("after sort")
    for (i in arr)
        print(i.toString() + ", ")
    println()
}

#2

Try

class MergeSort<T : Comparable<T>> {
...
}

That should help.
Int is Comparable<Int> and not Comparable<Any> (because you can only compare two Int, but you cannot compare Int with String)


#3

that solves it. thanks