Kotlin:将运算符作为函数参数传递

vto*_*tor 7 kotlin

我在Kotlin中有以下功能

fun evaluate(first:Int?, second:Int?) {
    var result = 0
    if (v.equals('*')) {
        result = (first ?: 0) * (second ?: 0)
    } else if (v.equals('+')) {
        result = (first ?: 0) + (second ?: 0)
    } else if (v.equals('-')) {
        result = (first ?: 0) - (second ?: 0)
    } else if (v.equals('/')) {
        result = (first ?: 0) / (second ?: 0)
    }
    return result   
}
Run Code Online (Sandbox Code Playgroud)

我想以某种方式更改它,以便我可以作为第三个参数传递所需的运算符并评估表达式.就像是

fun evaluate(first:Int?, second:Int?, op: () -> Unit):Int {
    return (first ?: 0).op(second ?: 0)
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如何将运算符作为函数传递?我检查了同样的问题,但目前尚不清楚如何通过运营商做到这一点.

Jay*_*ard 8

使用函数类型作为参数编写高阶函数允许使用内置运算符和lambda表达式进行操作,因此看起来像:

fun evaluate(first: Int?, second: Int?, op: (Int, Int) -> Int): Int {
    return op(first ?: 0, second ?: 0)
} 
Run Code Online (Sandbox Code Playgroud)

可以使用内置运算符调用,例如:

val r1 = evaluate(value1, value2, Int::times) 
val r2 = evaluate(value1, value2, Int::plus)
val r3 = evaluate(value1, value2, Int::minus) 
val r4 = evaluate(value1, value2, Int::div) 
Run Code Online (Sandbox Code Playgroud)

并具有自定义功能:

val r5 = evaluate(value1, value2) { a, b -> (a * a) + b }
Run Code Online (Sandbox Code Playgroud)

现在您还可以将运算符分配给变量,例如v:

val v: (Int, Int)->Int = Int::times  // typing needed on left to avoid ambiguous alternatives
// and then later...
val r6 = evaluate(value1, value2, v) 
Run Code Online (Sandbox Code Playgroud)

请注意,为签名编写的函数Int.(Int)->Int可以传递给期望的参数,(Int, Int)->Int因为接收器this将作为第一个参数传入.