在Kotlin中调用泛型方法参数

时间:2018-09-06 22:44:08

标签: kotlin

fun <T> doSum(a: T, b: T) : T {
    val result : Number = when {
        a is Int && b is Int -> a + b
        a is Long && b is Long -> a + b
        a is Float && b is Float -> a + b
        a is Double && b is Double -> a + b
        else -> throw IllegalArgumentException() 

    @Suppress("UNCHECKED_CAST")
    return result as T
}

fun <T: Number> doOperation(a: T, b: T, operationToPerform: (T, T) -> T ) {
    println(operationToPerform(a, b))
}

我有doOperations方法,该方法将泛型函数作为参数,我打算在传递的其他2个参数上运行。 但是,在main中调用与

相同:
fun main(args: Array<String>) {
    doOperation (2, 3, doSum)
}

返回如下错误:

Error:(15, 24) Kotlin: Function invocation 'doSum(...)' expected
Error:(15, 24) Kotlin: No value passed for parameter 'a'
Error:(15, 24) Kotlin: No value passed for parameter 'b'

关于使用doSum()调用doOperation的任何建议?

(&将 doSum更改为 doSum会引发另一个错误: 错误:(15,24)Kotlin:有趣的doSum(a:T,b:T):T中绑定到T的类型参数  不满足:推断类型(Int,Int)-> Int不是Number的子类型)

1 个答案:

答案 0 :(得分:1)

对于以后再来这里的任何人,这里的解决方法是像这样发送doSum(...)方法:

doOperation (2, 3, ::doSum)

::之前添加doSum(...)可以使您引用顶级,本地或成员函数。

更多信息:https://kotlinlang.org/docs/reference/lambdas.html#function-types