Functions help you organize code into reusable blocks. Lambdas let you write small, quick functions without naming them.
0
0
Functions and lambdas in Android Kotlin
Introduction
When you want to repeat a task multiple times without rewriting code.
When you need to pass a small piece of code as a parameter to another function.
When you want to keep your code clean and easy to read by breaking it into parts.
When handling user actions like button clicks with simple code blocks.
When working with collections to transform or filter data quickly.
Syntax
Android Kotlin
fun functionName(parameter: Type): ReturnType {
// code
}
val lambdaName: (Type) -> ReturnType = { parameter ->
// code
}Functions start with fun keyword, followed by name and parameters.
Lambdas are anonymous functions assigned to variables or passed directly.
Examples
A simple function that takes a name and returns a greeting.
Android Kotlin
fun greet(name: String): String {
return "Hello, $name!"
}A lambda doing the same greeting without a function name.
Android Kotlin
val greetLambda: (String) -> String = { name -> "Hello, $name!" }Short function that adds two numbers and returns the result.
Android Kotlin
fun add(a: Int, b: Int) = a + b
Lambda that adds two numbers, types are declared inline.
Android Kotlin
val addLambda = { a: Int, b: Int -> a + b }Sample App
This program shows a function and a lambda that both calculate the square of a number. It prints the results to the console.
Android Kotlin
fun main() {
fun square(x: Int): Int {
return x * x
}
val squareLambda: (Int) -> Int = { x -> x * x }
println("Function: square(4) = ${square(4)}")
println("Lambda: squareLambda(4) = ${squareLambda(4)}")
}OutputSuccess
Important Notes
Lambdas are great for short tasks but use functions for bigger, reusable code blocks.
You can pass lambdas directly to functions that expect them, like collection operations.
Use descriptive names for functions to make your code easier to understand.
Summary
Functions group code to reuse and organize it.
Lambdas are unnamed, quick functions useful for small tasks.
Both help keep your app code clean and easy to maintain.