iT邦幫忙

0

泛型extension function問題

各位前輩先進大家好:
我寫了一個泛型擴展函式如下:

 fun main(args: Array<String>) { 
     val listNum = listOf(9, 4, 5, 3)
     println(listNum.findBiggestNumber())
}

    fun <T> List<T>.findBiggestNumber():T{
        return this.sorted().last()
    }

執行後得到下列錯誤訊息:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public fun <T : Comparable<TypeVariable(T)>> Array<out TypeVariable(T)>.sorted(): List<TypeVariable(T)> defined in kotlin.collections
public fun ByteArray.sorted(): List<Byte> defined in kotlin.collections
public fun CharArray.sorted(): List<Char> defined in kotlin.collections
public fun DoubleArray.sorted(): List<Double> defined in kotlin.collections
public fun FloatArray.sorted(): List<Float> defined in kotlin.collections
public fun IntArray.sorted(): List<Int> defined in kotlin.collections
public fun LongArray.sorted(): List<Long> defined in kotlin.collections
public fun ShortArray.sorted(): List<Short> defined in kotlin.collections
public fun UByteArray.sorted(): List<UByte> defined in kotlin.collections
public fun UIntArray.sorted(): List<UInt> defined in kotlin.collections
public fun ULongArray.sorted(): List<ULong> defined in kotlin.collections
public fun UShortArray.sorted(): List<UShort> defined in kotlin.collections
public fun <T : Comparable<TypeVariable(T)>> Iterable<TypeVariable(T)>.sorted(): List<TypeVariable(T)> defined in kotlin.collections
public fun <T : Comparable<TypeVariable(T)>> Sequence<TypeVariable(T)>.sorted(): Sequence<TypeVariable(T)> defined in kotlin.sequences  

想請各位前輩幫忙,謝謝.

改成
fun <T: Comparable<T>> Iterable<T>.findBiggestNumber(): T {

return this.sorted().last()
}
了解,謝謝前輩指導.

尚未有邦友回答

立即登入回答