SoFunction
Updated on 2025-03-11

Introduction to the use of Kotlin anonymous functions

1. Function declaration

The declaration of functions in kotlin is different from that in java.

1) Must have fun keyword modification.

2) The declaration method of parameters is similar to that of variable declarations. age: Int, write the parameter name first, followed by the parameter type

3) The return value type is written after the parameter.

//Visibility modifier Function keywords Method name Parameter name Parameter type Return valueprivate       fun      functionName(age: Int, name: String): String {
    return name + age;
}

2. Function parameters

Default value parameter: If you do not intend to pass in a value parameter, you can set the default value for the parameter in advance

fun main() {
    //Usually called    fix("xiaohua", 20)
    //A has given the default value, and you can not pass parameters at this time    fix("xiaohua")
}
// Parameter age Given default valuefun fix(name: String, age: Int = 18) {
    println(name + age)
}

function

The function that does not have a return value in Kotlin is called the Unit function, which means that their return value is Unit

You can print the fix function defined above. The printed value is.

  println( fix("xiaohua"))

4. Anonymous functions

Functions that do not name when defined are called anonymous functions.

1) Declaration of named functions: The display will be modified using the fun keyword.

//Name functionfun sayHello(): String {
    return "Hello world!"
}
fun main() {
    //Name function call    println(sayHello())
}

Anonymous functions:

1) Although an anonymous function has no name, it can be assigned to a variable, and the type of this variable is the function type. Just like other variable assignments.

2) Unlike named functions, anonymous functions usually do not need the return keyword to return data. Anonymous functions will implicitly or automatically return the execution result of the last line of code.

Normal variable assignment:

 val hello: String = "hello"

Anonymous function assignment variable:

fun main() {
    //Declare an anonymous function and assign it to the variable saysHello    val sayHello: () -> String = {
        "Hello world!"
    }
    //Anonymous function call    println(sayHello())
}

3) Anonymous function type.

The type of a normal variable is specified when assigning, or through type inference, the compiler specifies the variable type in the compiler.

So what is the type of an anonymous function and what determines it?

The type of anonymous function is determined by the parameters and the return value.

fun main() {
    //Declare an anonymous function and assign it to the variable saysHello    val sayHello: () -> String = {
        "Hello world!"
    }
    //Print function variable    println(sayHello)
}

The result is Function0<>

Function0: The number after Function represents the number of parameters, 0 means no parameter, 1 means a parameter, and so on.

<> represents the value type of anonymous function.

5. Parameters of anonymous functions

Anonymous functions can be without parameters, or one parameter or multiple parameters.

When you need to take parameters, the parameter type is placed in the type definition of anonymous function "()" and the parameter name is placed in the function definition "{}".

1) Definition of a parameter:

fun main() {
    val sayHello: (name: String) -> String = { name ->
        "Hello $name!"
    }
    println(sayHello("HanMei"))
}

When there is only one parameter in an anonymous function, the it keyword can be used to represent the parameter name. It cannot be used when there are multiple parameters.

fun main() {
    val sayHello: (name: String) -> String = {
        "Hello $it!"
    }
    println(sayHello("HanMei"))
}

2) Define anonymous functions with multiple parameters

fun main() {
    val sayHello: (String, Int) -> String = { name, age ->
        "Hello $name$age"
    }
    println(sayHello("HanMei",18))
}

3) Type inference.

We know that when defining normal variables, you don't need to specify a type to the variable during the encoding stage.

When we assign anonymous functions to variables, we can also use the compiler to perform type inference without specifying the return value type of the function.

At this time, ": () -> String" when defining anonymous functions can be omitted.

Type inference when there is no parameter:

fun main() {
    val sayHello = {
        "Hello world!"
    }
    println(sayHello())
}

Type inference of a parameter:

Parameter definition and return value definition can be omitted. However, in the function definition, the parameter type and parameter name must be specified.

fun main() {
    val sayHello={ name:String ->
        "Hello $name!"
    }
    println(sayHello("HanMei"))
}

Type inference of multiple parameters:

fun main() {
    val sayHello = { name: String, age: Int ->
        "Hello $name$age!"
    }
    println(sayHello("HanMei", 18))
}

expression

We call anonymous functions lambda functions. Call his definition a lambda expression, and his return result is called a lambda result

7. Define parameters

Functions that define parameters are anonymous functions: the parameters of the function are another anonymous function.

1) First define a named function and receive an anonymous function as a parameter.

//Define a named function, receive a String parameter and a function parameter happyNewYear//happyNewYear: (name: String, year: Int) -> String This is the definition of anonymous functionfun sayhello(name: String, happyNewYear: (name: String, year: Int) -&gt; String) {
    val year = 2022
    //Calling the passed anonymous function in the named function    println(happyNewYear(name,year))
}

2) Define an anonymous function and pass it as a parameter when calling a named function.

fun main() {
    //Define an anonymous function    val happyNewYear = { name: String, year: Int -&gt;
        "${name},happy ${year}!"
    }
    //Call the named function and pass the anonymous function as a parameter    sayhello("HanMei", happyNewYear)
}

3) The anonymous function above can be defined not separately, but can also be defined when called.

Is this writing very similar to anonymous internal classes in java? The parameter of the method is new an interface to implement the methods in the interface.

fun main() {
    sayhello("HanMei", happyNewYear = { name: String, year: Int ->
        "${name},happy ${year}!"
    })
}

4) If lambda is the last parameter of a function, or the only parameter. Then, a pair of brackets that enclose the lambda value parameter can be removed.

fun main() {
    sayhello("HanMei") { name: String, year: Int ->
        "${name},happy ${year}!"
    }
}

8. Anonymous functions

Anonymous functions can also be used to extend Kotlin's built-in functions.

count is a built-in function Kotlin uses to calculate string lengths.

  val word = "HappyNewYear"
  var count = ()

Extend with anonymous functions

    count =  ({ letter ->
        letter == 'a'
    })

We know that when the last parameter of a function or only one parameter is a lambda, then the pair of parentheses can be omitted

count =   { letter -> letter == 'a' }

We also know that when there is only one parameter, it can be replaced by

count =  { it == 'a' }

9. Reference of functions

To pass a function as a parameter to other functions, in addition to lambda expressions, kotlin also provides other methods - function references

Function references can convert a named function into a value parameter and pass it to other functions.

Where lambda expressions are used, you can use function references.

1) First define two named functions:

happyNewYear is an ordinary function.

Sayhello can receive a function parameter. This function parameter can receive an anonymous function or a function reference.

fun happyNewYear(name: String, year: Int): String {
    return "$name happy $year"
}
fun sayhello(name: String, happyNewYear: (name: String, year: Int) -> String) {
    val year = 2022
    println(happyNewYear(name, year))
}

2) Use of function reference: double colon + function name, which is the reference of this function, which can be passed as a value parameter

fun main() {
    //::happyNewYear is a reference to the function.    sayhello("HanMei",::happyNewYear)
}

10. Function type as return type

The return value of a function can be another function, and the function type is also a valid return value type.

Sayhello is a method without parameters. The return value type is (String) -> String. This expression means an anonymous function with a parameter of String type and a return value of String type.

fun sayhello(): (String) -> String {
    return {
        val year = 2022
        "$it happy $year"
    }
}

Calling method:

fun main() {
    //Call sayhello to get this anonymous function and assign it to the variable happyNewYear    val happyNewYear = sayhello();
    //happyNewYear is an anonymous function that can be called directly by passing parameters    println(happyNewYear("HanMei"))
}

Note that the above returns anonymous function with such a code, val year = 2022; This is defined in anonymous function.

It can also be defined in the named function outside, and the anonymous function can still be accessed.

fun sayhello(): (String) -> String {
    val year = 2022
    return {
        "$it happy $year"
    }
}

This is another concept. Closure

In Kotlin, anonymous functions can modify and refer to variables defined outside their scope, while anonymous functions refer to variables in the function that defines itself. That is to say, the anonymous function returned by sayshello can refer to the variable of the function that defines it.

Kotlin's lambda is the closure.

This is the article about the introduction to the use of Kotlin anonymous functions. For more related content of Kotlin anonymous functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!