Kotlin: Passing an operator as a function parameter

I have the following function in 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   
}

I want to change it so that I can pass the necessary operator as the third parameter and evaluate the expression. Sort of

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

How can I pass an operator as a function in this case? I checked the same type of question , but it is not clear how you can do this with the operator.

+4
source share
3 answers

Writing a higher-order function using the function type as a parameter allows you to use both built-in operators and lambda expressions for the operation, so it will look like this:

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, this .

+6

() -> Unit Int.(Int) -> Int. , .

this - int, - int: { other -> this * other }

0

:

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,"+"))
}
0

Source: https://habr.com/ru/post/1654450/


All Articles