Kotlin: Functions Cheat Sheet

Function types

()->Unit – takes no arguments and returns nothing (Unit).

(Int, Int)->Int – takes two arguments of type Int and returns Int.

(()->Unit)->Int – takes another function
and returns Int.

(Int)->()->Unit – takes an argument of type Int and returns a function.

Function literals

Simple lambda expression

val add: (Int, Int) -> Int = { i, j -> i + j }
val printAndDouble: (Int) -> Int = {
    println(it)
    // When single parameter, we can reference it using it
    it * 2 // In lambda, last expression is returned
}

Anonymous function alternative

val printAndDoubleFun: (Int) -> Int = fun(i: Int): Int {
    println(i) // Single argument can’t be referenced by it
    return i * 2 // Needs return like any function
}

Extension functions

fun Int.isEven() = this % 2 == 0 
print(2.isEven()) // true 
fun List.average() = 1.0 * sum() / size 
print(listOf(1, 2, 3, 4).average()) // 2.5

Leave a Reply

Your email address will not be published. Required fields are marked *