Kotlin Lambda Functions and Anonymous Functions Comprehensive Guide

Kotlin Lambda Functions and Anonymous Functions

Before we start let’s remember important point from my previous blog

📝📝 ✨✨✨✨✨✨✨✨✨✨NOTE✨✨✨✨✨✨✨✨✨✨✨📝📝

✨In Kotlin, functions are considered first-class citizens, which means they can be treated like any other data type, such as integers or strings.

✨There are different ways to define functions, and the choice between them often revolves around how explicitly you want to specify certain details. 

Kotlin Lambda Functions and Anonymous Functions

What is lambda function in Kotlin?

Lambda functions, often referred to simply as “lambdas” in programming, are a way to define small, anonymous functions in a more concise and expressive manner. They are a fundamental concept in many modern programming languages, including Kotlin.

Kotlin Lambda Functions and Anonymous Functions

Syntax of a Lambda Function:

val lambdaName: (parameter1Type, parameter2Type, ...) -> returnType = { parameter1, parameter2, ... -> // lambda body }
Kotlin
  • lambdaName: This is an optional variable name that can be used to reference the lambda.
  • (parameter1Type, parameter2Type, ...): These are the types of parameters the lambda function takes.
  • returnType: This specifies the type of value that the lambda function returns.
  • { parameter1, parameter2, ... -> // lambda body }: This is the actual lambda function, where you define its behavior. It takes parameters and has a body where you specify what the function does.

Lambda functions are like mini-magicians in the coding universe. They are compact, anonymous functions that can perform tasks without a formal name. Think of them as magical wands that allow you to cast spells (functions) without creating a lengthy ritual (function declaration). Let’s break down their structure:

val sum: (Int, Int) -> Int = { a, b -> a + b }
Kotlin

In this example, sum is a lambda function that takes two integers (a and b) as parameters and returns their sum. The -> separates the parameters from the function body, making lambda functions concise and expressive.

Integration with Higher-Order Functions:

Lambda functions shine brightest when used with higher-order functions. They allow you to pass behavior (functions) directly into other functions, enhancing the flexibility of your code. Consider a scenario where you want to filter a list of tasks based on their completion status. Lambda functions make this task effortless:

val tasks = listOf(Task("Read a Book", true), Task("Write Code", false), Task("Exercise", true))

val completedTasks = tasks.filter { task -> task.isCompleted }
Kotlin

In this example, the filter higher-order function uses a lambda to determine which tasks are completed. The { task -> task.isCompleted } lambda checks each task’s completion status and filters the list accordingly.

Imagine you have a list of Android apps, and you want to sort them alphabetically by name. Lambda functions make this task elegant and straightforward:

data class AndroidApp(val name: String, val rating: Double)

val apps = listOf(AndroidApp("Maps", 4.5), AndroidApp("Calendar", 4.2), AndroidApp("Music", 4.8))

val sortedApps = apps.sortedBy { app -> app.name }
Kotlin

In this example, the sortedBy higher-order function uses a lambda to specify the sorting criterion (app.name). The list of Android apps is sorted alphabetically by their names, creating an organized app list.

Lambda functions empower Android developers to write concise, expressive, and readable code. They are invaluable tools in your coding arsenal, allowing you to create efficient and elegant Android applications.

Example 1: Filtering a List

val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter { it % 2 == 0 }
Kotlin

In this example, we have a list of numbers. We use the filter function, which takes a lambda function as an argument. The lambda function { it % 2 == 0 } defines a condition that checks if a number is even. The filter function applies this condition to each element in the numbers list and creates a new list called evenNumbers containing only the even numbers.

Example 2

Let’s say we have a list of names, and we want to filter out all the names that start with the letter “A.” We can use a Lambda Function for that:

fun main() {
    val names = listOf("Alice", "Bob", "Charlie", "Anna", "David")

    val filteredNames = names.filter { name -> name.startsWith("A") }

    println("Original names: $names")
    println("Filtered names (starting with 'A'): $filteredNames")
}
Kotlin
  1. We start with a list of names.
  2. We use the filter function, which takes a Lambda Function as an argument. This Lambda Function name -> name.startsWith("A") means “check if a name starts with the letter ‘A’.” If it does, keep it; otherwise, discard it.
  3. The filter function goes through each name in the list and applies our Lambda Function to it.
  4. Names that start with “A” are kept, and the rest are removed.

When we run this code, we’ll see the following output:

Original names: [Alice, Bob, Charlie, Anna, David]
Filtered names (starting with 'A'): [Alice, Anna]
Kotlin

As you can see, the Lambda Function helps us filter the list of names and gives us a new list with only the names that start with “A.”

Lambda Functions are really useful because they allow you to write custom, small pieces of code for specific tasks without the need to define a separate function with a name. It makes your code more concise and expressive!

Checking for Prime Numbers

fun main() {
    val numbers = listOf(2, 3, 4, 5, 6, 7, 8, 9)

    val primes = numbers.filter { number ->
        var isPrime = true
        if (number <= 1) {
            isPrime = false
        } else {
            for (i in 2 until number) {
                if (number % i == 0) {
                    isPrime = false
                    break
                }
            }
        }
        isPrime
    }

    println("Numbers: $numbers")
    println("Prime numbers: $primes")
}
Kotlin
  • We have a list of numbers.
  • We use the filter function with a more complex Lambda Function to filter out prime numbers. The Lambda Function checks if each number is prime or not.
  • To determine if a number is prime, we iterate through all numbers from 2 up to one less than the number itself. If we find any number that evenly divides the given number, it’s not prime.
  • We print out both the original list of numbers and the list of prime numbers.
Numbers: [2, 3, 4, 5, 6, 7, 8, 9]
Prime numbers: [2, 3, 5, 7]
Kotlin

What are anonymous functions used for?

In Kotlin, an anonymous function is a way to define a function without giving it a specific name. It combines elements of both regular named functions and lambda expressions, providing a more explicit syntax while still allowing for flexibility.

Anonymous functions are declared using the fun keyword, followed by the parameter list, an optional explicit return type, and the function body.

val sum = fun(a: Int, b: Int): Int {
    return a + b
}
Kotlin

Anonymous functions are often used in scenarios where a more formal syntax is preferred over the concise syntax of lambda expressions. They can be particularly useful when the function logic is more complex and spans multiple lines.

  • They are particularly useful in cases where the code logic is specific to a certain context or event and doesn’t need a dedicated named function.
  • Remember that the choice between anonymous functions and other function types depends on the specific requirements and readability considerations in your Android project.

Kotlin Functions

Advanced Functions Higher-Order Functions – Lambda Functions – Extension Functions – Infix Functions- Generic Functions
See More Info

Functions– Simple Functions – Function Parameters – Function Return Types – Function Scope
See More Info

Functional Programming FunctionsImmutability and Pure Functions- Function Composition – Functional Operators
See More Info

Feel free to follow and join my email list at no cost. Don’t miss out — sign up now!

Please check out my earlier blog post for more insights. Happy reading!

The Innovative Fundamentals of Android App Development in 2023

How to learn Android App Development in 2023 – Full Guide For Beginners using Kotlin Language

What is the Repository Pattern in Android? A Comprehensive Guide

What is ViewModel in Android? A Good Guide for Beginners

The Innovative Fundamentals of Android App Development in 2023

How to Say Goodbye to Activity Lifecycle and Say Hello to Compose Lifecycle ?

How to Monitor/Observe Network Availability for Android Projects

Exploring Sealed Class vs Enum in Kotlin Which is Best for Your Code?

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x