Kotlin Lambda Function with Single Parameter

Kotlin Lambda Function with Single Parameter

In Kotlin, lambda functions are anonymous functions that can be used as a concise way to define functionality. Lambda functions with single parameters are common and provide a simplified syntax for writing functions.

Step 1: Define a Lambda Function

Create a lambda function with a single parameter. The syntax for a lambda function with a single parameter is { parameter -> expression }.

val square: (Int) -> Int = { number -> number * number }

Step 2: Use the Lambda Function

Invoke the lambda function by passing an argument to it.

val result = square(5) // Invoking the lambda function with an argument
println("Square of 5 is $result")

Complete Kotlin Program

Following is the complete Kotlin program demonstrating the use of a lambda function with a single parameter.

Kotlin Program

fun main() {
    val square: (Int) -> Int = { number -> number * number }
    val result = square(5)
    println("Square of 5 is $result")
}

Output

Kotlin Lambda Function with Single Parameter - Example output

Summary

By following these steps and using the { parameter -> expression } syntax, you can create and use lambda functions with single parameters in Kotlin. Lambda functions provide a concise way to define functionality without the need for explicitly naming functions.