Kotlin High Order Functions

In high-order function, we can pass a function as a parameter to the other function. This means in addition to passing variables as parameters to the function, we can pass the function and the function return type can also be a function.

Example

fun highOrderFunc(x: String,y: String, msg: (String,String) -> String): Unit {
	val x = "Hello John "
	val y = "How are you? "
	val message = msg(x,y)
	println(message)
}

In the above example, the highOrderFunc() function has three parameters, first and second are strings, and the third parameter is a function.

fun highOrderFunc(x: String,y: String, msg: (String,String) -> String): Unit {
    val message = msg(x,y)
    println(message)
}
fun main(args : Array<String>)  {  
    val x = "Hello John! "
    val y = "How are you? "
    val msg:(String,String)->String={x,y->"$x $y"}
    highOrderFunc(x,y,msg)
} 
Output
Hello John!  How are you? 






Read more articles


General Knowledge



Learn Popular Language