Search⌘ K

Kotlin Lambdas and Higher-Order Functions

Explore Kotlin's lambdas and higher-order functions to understand how to create and use anonymous functions, pass functions as parameters, and write concise reusable code in Android development.

Functions

Kotlin uses the keyword fun to declare functions, which can take parameters and return values. Here’s an example of declaring a function in Kotlin:

Kotlin
fun main(){
greet("Adam", "evening")
}
fun greet(name : String, timeOfDay : String) {
println("Good $timeOfDay, $name!")
}

In the code above, we declare a greet function which takes two parameters: name and timeOfDay. The function prints a message to the console that includes both parameters.

Function return types

We can also define a return type for a function, which specifies the type of value the function returns. We define the return type after the parameter list, using the colon notation. Here’s an example of a function that returns a string:

Kotlin
fun main(){
print(getGreeting("Adam", "evening"))
}
fun getGreeting(name : String, timeOfDay : String) : String {
return "Good $timeOfDay!, $name."
}

In the code above, we define a getGreeting function that takes two parameters, name and timeOfDay, to return a ...