1 Anonymous Function

  • Common function
//Kotlin
fun f1(a) {
    println("Hello")}Copy the code

This is an ordinary function that omits its type, which has its own name f1 and is of type ()->Unit.

  • Anonymous functions
//Kotlin
val f2 = fun(a) {
    println("Hello")}Copy the code

To the right of the above assignment number is an anonymous function without a function name. You can assign to the variable f2 and invoke f2() or f2.invoke() to invoke the anonymous function.

Like normal functions, the function type of this anonymous function is ()->Unit.

2 Lambda expressions

Lambda expressions are essentially more expressive anonymous functions.

2.1 Definition of Lambda expressions

The Kotlin Lambda expression in the figure has a function type of ()->Unit. You can’t omit parentheses without passing in arguments in Java, and you can omit parentheses in Kotlin.

Lambda expressions were added in Java 8 and type derivation var was added in Java 10, but the types of Lambda expressions in Java cannot be type derived, essentially because functions (methods) in Java are not types and are not “first-class citizens.” Therefore, the declaration type needs to be displayed, and generally a SAM(Simple Abstract Method) interface is defined to define the type of the Lambda expression.

The Lambda expression in Java above uses SAM to define the type of the expression.

In Kotlin, a Lambda expression is normally defined as follows:

//Kotlin
val lambda0: () -> Unit = {
    println("Hello")}val lambda1: (Int) - >Unit = {
    println(it)
}

val lambda2: (Int, String) -> Unit = { i: Int, s: String ->
    println("$i $s")}Copy the code

2.2 Derivation of Lambda expression types

  • Type of a Lambda expression if it has no input arguments()->Any?Can be omitted
  • The type of the last line of a Lambda expression is the return type of the entire expression

Such as:

If an expression is used as an input parameter, it must explicitly declare the type of each input parameter. Otherwise, an error is reported:

In general, it is important that the compiler be able to deduce the type of the passed parameter.

summary