Kotlin

Lambda, Filter, and Map Function In Kotlin

As the title of this article described today’s piece cover using lambda, map, and filter in Kotlin. We’ll be covering the syntax and usage of each function and walk through some examples to familiarize yourself with using them.

So, let’s get started with the lambda definition.

What is Lambda Function

Kotlin allows you to create a one-time anonymous function, function having no names using a facility called lambda function. Lambda functions are small usually not more than one line.

Before showing you the basic syntax of how to write a lambda expression, I want to show you the simple function in Kotlin.

fun multiply(x : Int, y: Int) : Int {
    return x * y
}

The above function name is multiply, it expects two arguments x and y with type Int and returns their multiplication.

Now let’s see how we can convert the above function in lambda function.

Basic Syntax of Lambda Function

The full syntax of a kotlin lambda expression is as follows:

val multiply: (Int, Int) -> Int = { x, y -> x * y }

fun main() {
   print(multiply(5, 4))
}

// Output
20

In the above code at the left of -> is the parameter type, enclosed in parentheses (Int, Int). The result type indicating on the right side of the arrow. The definition of the function comes after = sign. It’s enclosed between braces and takes the form of the lambda expression.

The lambda expression returns the multiplication of two numbers as an Int type number and assigns to the multiply variable.

In last we simply call the multiply expression as we’re calling any basic function.

You can also omit the type of lambda expression like this:

val multiply = {x: Int, y: Int -> x * y}

fun main() {
    print(multiply(5, 4))
}

Protip:

If you prefer shorter type name, you can create an alias at project-level:

typealias IntOperation = (Int, Int) -> Int

val multiply : IntOperation = {x ,y -> x * y}

fun main () {
   print(multiply(5 ,4))
}

To make our typealias more reusable you can change it into a more generic style.

typealias PolymorphicOperation<T,U> = (T, T) -> U

val add : PolymorphicOperation<Int,Float> = {x, y -> (x + y).toFloat()}
val multiply : PolymorphicOperation<Float, Double> = {x , y -> (x * y).toDouble()}

fun main() {
    println(add(5, 4))
    print(multiply(5.0F, 4.0F))
} 

// Output of above program
9.0
20.0

Filter Function

As the name suggests, the filter function filters all those items that pass the predicate (some sort of if condition) test. Before showing you the magic of filter function I wanna show you how we apply the filter function manually without using the functional-programming approach.

Now let’s say I have the list of Person and I want all those persons whose ages greater than or equals to 25.

data class Person(val name : String, val age: Int)

val persons = listOf(Person("Ahsen Saeed", 23), Person("Post Mallone", 28), Person("Elizbeth", 30)) 

fun main() {
   val result = mutableListOf<Person>()
   for(person in persons) {
       if(person.age >= 25)
          result.add(person)
   }
   print(result)
}

// Output
[Person(name=Post Mallone, age=28), Person(name=Elizbeth, age=30)]

You see at the above we’re creating everything on our own instead of using the _Collection class utility function. Now let’s see the magic of filter, I’m pretty sure you’ll love the most and use it in your day-to-day development.

Basic Syntax of Filter Function

Note: The filter function is only applicable to collection classes.

data class Person(val name : String, val age: Int)

val persons = listOf(Person("Ahsen Saeed", 23), Person("Post Mallone", 28), Person("Elizbeth", 30)) 

val agePredicate: (Person) -> Boolean = { person: Person -> person.age >= 25 }
fun main() {
    val result = persons.filter(agePredicate)
    print(result)
}

// Output
[Person(name=Post Mallone, age=28), Person(name=Elizbeth, age=30)]

As you can see above the agePredicate is a lambda function accepting Person as input and returns true if the person.age is greater than or equal to 25 else false.

The filter accepts the lambda as input, applies the predicate condition on every item inside the list, and returns a new list containing all the items that pass the predicate condition.

You can also pass the predicate directly inside the filter function like below.

data class Person(val name : String, val age: Int)

val persons = listOf(Person("Ahsen Saeed", 23), Person("Post Mallone", 28), Person("Elizbeth", 30)) 

fun main() {
    val result = persons.filter{ it.age >= 25 } // it is person object
    print(result) 
}

// Output same as above program

Map Function

Think of map function as some kind of transformation, applies a function (a lambda) to all the items and return a list of items modified by the function. Let’s see how we can use the map function on a Person collection.

data class Person(val name : String, val age: Int)

val persons = listOf(Person("Ahsen Saeed", 23), Person("Post Mallone", 28), Person("Elizbeth", 30))

fun main() {
    val result = persons.map{ person ->
         "${person.name} is ${person.age} years old"
    }
    print(result)
}

// Output
[Ahsen Saeed is 23 years old, Post Mallone is 28 years old, Elizbeth is 30 years old]

In the above example, the map executes the lambda function for each person inside the collection and returns a list of string.

Let’s see the above example by using function reference (pass it to another function) instead of directly passing the lambda.

data class Person(val name : String, val age: Int)

val persons = listOf(Person("Ahsen Saeed", 23), Person("Post Mallone", 28), Person("Elizbeth", 30))

fun transformPerson(person : Person) : String {
    return "${person.name} is ${person.age} years old" 
}

fun main() {
    val result = persons.map(::transformPerson)
    print(result)
}

// Output of above program
[Ahsen Saeed is 23 years old, Post Mallone is 28 years old, Elizbeth is 30 years old]

Alright, guys, if you enjoyed this article kindly spread the word and don’t forget to hit the ♥️ button. To get updates for my new stories, subscribe to my website on the home page.

Thank you for being here and keep reading…

More Resource

10 Kotlin List Tips & Tricks

Write A Comment