Lambda expressions in Kotlin

Lambda expressions in Kotlin

In Java 8, one of the features that were added was lambda functions. Unsurprisingly, this feature is available in Kotlin as well, with slight differences. So what is a lambda expression? A lambda expression is simply a block of code (normally short) that takes in parameters and uses them to return a value. This is similar to a normal method but with the following two differences:

  1. A lambda does not need a name
  2. A lambda can be implemented within the method body

Declaring lambdas

Before actually diving into the declaration of lambdas, it is likely that you have already used them either knowingly or unknowingly. In any case, the syntax in Kotlin is as follows:

val name : Type = { parameters -> body }

If you wish to have more than one parameter, then you wrap them in parentheses as follows:

val name : Type = { (param1, param2) -> body }

Let us say that we want to calculate the square root of a number with a lambda. The expression would be declared as follows:

val squareRoot = { number: Int -> sqrt(number.toDouble()) }

// Calling this with 40 as the argument
fun main() {
    println(squareRoot(400))
}

// Will print
20.0

The above lambda can also be re-written as follows with type annotation in play:

val squareRoot: (Int) -> Double = { number -> sqrt(number.toDouble()) }

The above code will work just like the other one did, although it has a slight difference in how it is written. You are better off just using the first approach and let the power type inference in Kotlin handle the rest for you. Additionally, you do always need the variable as it can be passed as the function argument. Use the second approach if you feel the need to specify the return type explicitly.

Note: The number of parameters in your lambda will determine the number of arguments once you call the lambda.

The lambda's last line is the returned value, which means you can change the type returned if you want. If nothing is returned, you can use Unit. Consider the following code that returns an integer:

val multiplication = { a: Int, b: Int -> a * b }

With a slight modification, the code now returns a double from the lambda operation:

val multiplication = { a: Int, b: Int ->
    val res = a * b
    res.toDouble()
}

Usage in extension functions

If you do not know what extension functions are, I advise you to look at my brief introduction here. If you are familiar with them, then go ahead reading.

You can use a lambda as part of an extension function. For example, say that you want to check that a string has a length greater than an integer. You can use the following code for this, and it would work just fine:

fun String.validateString(size: Int): String {
    return if (this.length > size) this else "Invalid string"
}

You can do the same thing with a lambda, and the result would still be the same then you can proceed to use the string in your code:

val greaterThanString: String.(Int) -> String = {
    if (this.length > it) this else "Invalid string"
}

You will notice that there is an it keyword that has been used. The it refers to the single parameter that we used, which, in our case, is the Int.

Final words

Lambdas have been a struggle for me in the past in trying to understand how they work, so do not feel discouraged if you do not understand the concept at first. Just go through it and leave a comment if you have one.

Until next time!

PS Let us connect on Twitter , GitHub , and Linkedin . You can follow me on Hashnode as well and let us build awesome things together.