Saturday 25 May 2019

Kotlin Lambda Expression & HO Functions - Quick Reference

Lambda Expression: As we know, syntax of Kotlin lambdas is similar to Java Lambdas. A function without name is called anonymous function. For lambda expression we can say that it is anonymous function. A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value.

Higher-Order Function: In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.

class Operators {
    fun add(a: Int, b: Int) = a + b
    fun inc(a: Int) = a + 1
}

fun calculate(a: Int, b: Int, opr: (Int, Int) -> Int) = opr(a, b)
fun calculate(a: Int, opr: (Int) -> Int) = opr(a)

val addition = { a: Int, b: Int -> Operators().add(a, b) }
fun addition(a: Int, b: Int) = Operators().add(a, b)

val increment = { a: Int -> Operators().inc(a) }
fun increment(a: Int) = Operators().inc(a)

fun main() {
    println("Output: " + calculate(1, 2) { a, b -> Operators().add(a, b) }) // Lambda as param
    println("Output: " + calculate(1, 2, Operators()::add)) // Function as param - reference through its object
    println("Output: " + calculate(1, 2, addition)) // Lambda Expression as param
    println("Output: " + calculate(1, 2, ::addition)) // Function as param
    println("")
    println("Output: " + calculate(1) { a -> Operators().inc(a) }) // Lambda as param
    println("Output: " + calculate(1) { Operators().inc(it) })  //Lambda as param Since it is the only param so, `it` referenced here
    println("Output: " + calculate(1, Operators()::inc)) // Function as param - reference through its object
    println("Output: " + calculate(1, increment)) // Lambda Expression as param
    println("Output: " + calculate(1, ::increment)) // Function as param
}

Output: 3
Output: 3
Output: 3
Output: 3

Output: 2
Output: 2
Output: 2
Output: 2
Output: 2

Happy Coding :-)