Anonymous function
package examples

fun main() {
    var f = {
        println("hello")
    }() // print hello
}

Function type
package examples

fun main() {
    {
        println("construstor ")
    }()
    var f = {
        println("hello f1")
    }

    val f2: () -> Unit = {
        println("hello f2")
    }

    f()
    f2()
}

Implicit Return
  • Anonymous function support return last line of value
package examples
fun main() {
    var f = { //
        "implicit return"
        "ABC" // Print ABC
    }
    println(f())
}

Anonymous Function argument
package examples

fun main() {
            // arg types                return type   arg names
    val f : (String, String, String) -> Int =         {a, b, c ->
        a.length + b.length + c.length
    }
    println(f("aa", "fff", "ee"))
}

Default argument name: it
  • "it" is the default argument name when there is only one parameter in anonymous function
package examples

fun main() {
    val f : (String) -> Int = {
        it.length
    }
    println(f("Gss"))
}

Return type inference
  • No need to specify return type
package examples

fun main() {
    val f = {
        "hello"
    }
    println(f())
}
  • Need provide arg name when no return type specified
package examples

fun main() {
    val f = { name:String ->
        "hello $name"
    }
    println(f("FF"))
}

Function as argument
package examples

fun main() {
    println(count("hello", {it == 'l'}))
}

fun count(s:String, exclude:(Char) -> Boolean): Int {
    var result = 0
    for (c in s) if (!exclude(c)) result++
    return result
}
  • Lambda argument should be moved out of parentheses (Intellij suggestion)
    (When function is the latest argument)
package examples

fun main() {
    println(count("hello") {it == 'l'})
}

fun count(s:String, exclude:(Char) -> Boolean): Int {
    var result = 0
    for (c in s) if (!exclude(c)) result++
    return result
}

Function Inlining
  • Inlining removes the need for the JVM to use an object instance and to perform variable memory allocations for the lambda.
package examples

fun main() {
    println(count("hello") {it == 'l'})
}

inline fun count(s:String, exclude:(Char) -> Boolean): Int {
    var result = 0
    for (c in s) if (!exclude(c)) result++
    return result
}

Function Reference
  • Use "::" to reference a function
package examples

fun main() {
    run(::printHello)
}

fun run(f: () -> Unit) {
    f()
}

fun printHello() {
    println("hello")
}

Return Function Type
package examples

fun main() {
    create()("john")
}

fun create(): (String) -> Unit {
    return {
        println("hello $it")
    }
}


Tags:

Updated: