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 } 

我想以某种方式改变它,以便我可以将第三个参数作为必要的运算符并评估表达式。 就像是

 fun evaluate(first:Int?, second:Int?, op: () -> Unit):Int { return (first ?: 0).op(second ?: 0) } 

在这种情况下,我怎样才能把操作符作为一个函数呢? 我查了同样的一个问题 ,但不清楚你怎么可以做到这一点与运营商。

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

 fun evaluate(first: Int?, second: Int?, op: (Int, Int) -> Int): Int { return op(first ?: 0, second ?: 0) } 

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

 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) 

并与自定义功能:

 val r5 = evaluate(value1, value2) { a, b -> (a * a) + b } 

现在,您也可以将操作符分配给变量,例如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) 

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

() -> Unit更改为Int.(Int) -> Int 。 那么所有其他的代码应该像你在那里写的那样工作。

在调用方面, this是第一个int,第一个参数是第二个int: { other -> this * other }

你可以尝试做到这一点:

 fun evaluate(first: Int?, second: Int? , v:String ): Int = v.op(first ?: 0, second ?: 0) fun String.op(first:Int,second:Int):Int = when (this) { "*" -> first * second "+" -> first + second //.... else -> throw Exception() } fun main(args: Array<String>) { println(evaluate(2,3,"*")) println(evaluate(2,3,"+")) }