Dima Sidukov
Dima Sidukov

Reputation: 69

Proper use of Number class in Kotlin

Can anyone help me implement these methods in Kotlin? I want to find min, max elements of array of numbers and also sort array in ascending order. Here is a code

class DataArray<Number>(vararg numbers: Number) {
    private val array = mutableListOf<Number>(*numbers)

    fun getMin() {
        return array.minByOrNull { it! } //doesn't work
    }

    fun getMax() = array.max() //doesn't work
    fun sort() = array.sort()  //doesn't work


    private fun <E> MutableList<E>.max(): Any { //was created to use in function above, but resulted in stack overflow
        return this.max()
    }

    private fun <E> MutableList<E>.sort(): Any { //was created to use in function above, but resulted in stack overflow
        return this.sort()
    }

    override fun toString(): String {
        var str = ""
        for(i in array)
            str += "$i "
        return str
    }
}

fun main() {

    val arr = DataArray(2, 5, 2, 6, 9, -3, 56, 16, 72, 8)
    println(arr.getMax())
    println(arr.getMin())
    println(arr.sort())
    print(arr)
}

Upvotes: 0

Views: 377

Answers (1)

Sweeper
Sweeper

Reputation: 274480

Note that the word Number here declares a generic parameter called Number. It does not refer to kotlin.Number. You might have intended it to declare a generic parameter with a bound of Number instead, in which case you should have written:

class DataArray<T: Number>(vararg numbers: T) {
    ...
}

But even if you did, it still wouldn't work as Numbers are not comparable.

You would have to further constrain T to Comparable<T>:

 class DataArray<T: Number>(vararg numbers: T) where T: Comparable<T> {

Then you can do:

fun getMin() = array.minOrNull()
fun getMax() = array.maxOrNull()
fun sort() = array.sort()

Extension functions on MutableList are unnecessary.

(Note that technically, the T: Number constraint is also unnecessary if you just want to use minOrNull, maxOrNull, and sort. I'm assuming you are planning on using one of the methods in kotlin.Number. Otherwise you can delete that constraint.)

You seem to be trying to implement your own MutableList by delegation. Keep in mind that you can easily do this using by:

class DataArray<T: Number>(
        vararg numbers: T
) : MutableList<T> by mutableListOf(*numbers) {
    override fun toString(): String {
        var str = ""
        for(i in this) // rather than "array", use "this"
            str += "$i "
        return str
    }
}

Upvotes: 3

Related Questions