Kotlin Basics: Lambda Syntax

January 01, 2020

Happy New Year! 🎉

I intend to start writing about some more complex Kotlin concepts, but I’d like to lay a bit of groundwork first.

Lambda Functions

Lambda functions are little chunks of code that can be passed around in functions [1]. They’re usually concise, single-minded, and anonymous.

The main benefit is that they can be executed by the function we pass them into. This gives the language space for a lot of declarative, functional APIs.

We’re usually saying, to the function we’re calling, something along the lines of:

“Map the collection to a new one using this lambda function.”

“Create a new collection containing only items filtered using this lambda function.”

Kotlin’s Syntax

When we have a function that takes in a lambda, we can pass it in directly, like we do in most programming languages.

listOf(1, 2, 3).map({ num -> num * num })

There is, however, a nice shortcut where we can omit the -> and use the implicit it parameter. The following is equivalent to the first example:

listOf(1, 2, 3).map({ it * it })

If the last parameter of the function we’re using (map, in this case) is a function, then we can place it outside of the parenthesis. If it’s the only paremeter, we don’t even need parenthesis. This is a Kotlin convention.

listOf(1, 2, 3).map { it * it }

For an example of a function with a multiple parameters, we can consider the fold function. fold is just like reduce, except we’re reducing to a different type than the input.

Here’s an example—write a function that counts the number of times a letter occurs in a string.

fun letterCount(string: String, letter: Char) = string.fold(0) { acc, current: Char -> if (current.equals(letter)) acc + 1 else acc }

The point of the above is just that the following are equivalent:

foo(a, { /* lambda function */ })
foo(a) { /* lambda function */ }

Note that if you ever have to implement a letterCount function, use Kotlin’s count function instead.

Looking forward to some more complex Kotlin posts :).


  1. Kotlin in Action
  2. Kotlin docs

Join the mailing list

Get the latest posts in your inbox. No spam, ever.