Kotlin miniguide #14 High order functions

In Kotlin, functions can be passed as arguments to other functions, returned from functions, stored in variables.

In the code below a function add is declared as a lambda and passed as argument to the function calc:


val add ={a: Int, b: Int ->a+ b}

fun calc(i1:Int, i2: Int, action : (p1: Int, p2: Int) -> Int) {

var result = action (i1, i2)

}

//usage

calc(add)

In the code below a function add is declared as an anonymous function and passed as argument to the function calc:


val add =fun(a: Int, b: Int) =a+ b

fun calc(i1:Int, i2: Int, action : (p1: Int, p2: Int) -> Int) {

var result = action (i1, i2)

}

//usage

calc(add)

Returning a function that accepts a string and returns nothing:


fun displaMsg(msg : String) : (String) -> Unit {

return { s -> println ("$msg is $s" ) }

}

val d = displayMsg("error")

d("401")

//output is "error is 401"

Lascia un commento