Language Elements

Data Types

Kotlin Nullable Types

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Collections

Kotlin Example Codes

Kotlin Interview Questions

Lambda functions define small, anonymous functions that can be used as arguments to higher-order functions, or as a way to define inline functions without having a name. These functions without any user-defined names are very useful for short, simple operations used in a specified context, and create more cleaner and readable code.

The basic syntax follows:

{ parameters -> body }

'{' and '}' denote the lambda function.
'->' separates the parameters from the body of lambda.
'body' is the code that gets executed when lambda is invoked.

Kotlin Lambda Function Examples

Expressing lambdas as expression:

    
val add: (Int, Int) -> Int = { a, b -> a + b }
    
val sum = { a: Int, b: Int -> a + b }
    
val printMessage: (String) -> Unit = { message -> println(message)}

val multiply = { a, b -> a * b } // Compiler infers parameter types
    
Using Lambda Functions
    
val add: (Int, Int) -> Int = { a, b -> a + b }
val result = add(3, 4) // result is now 7

// Inline usage without storing in variables
val numbers = listOf(1, 2, 3, 4, 5)

val squaredNumbers = numbers.map {number -> number * number }

val sum = numbers.reduce { acc, num -> acc + num }


Copyright © by Zafar Yasin. All rights reserved.