Understanding Kotlin’s Lambda Expressions and Higher Order Functions Part 1(a)

Matheka Mwanzia
DevCNairobi
Published in
2 min readFeb 5, 2020

In this short tutorial, we’ll try to understand Kotlin’s lambda expressions and higher order functions in the most basic way possible. It’s important to note that this piece is in a little effort to make you understand the concept. And Its goal is not to make you master the content but instead get a grasp of what Lambda expressions and higher order functions entail. With that out of the way twende kazi (Let’s begin)

Lambda Expressions

Lambda

First, let’s understand lambda expressions.

-A lambda expression is an anonymous function that provides a concise and functional syntax.

Well, that definition is quite vague for a beginner. Let’s further decipher it, shall we? In the most layman definition, a lambda expression is a simplified representation of a function. In that, it’s an anonymous function (a function without a name) that we can treat as a value.

This anonymous function is passed immediately as an expression without a declaration.

Let’s further check its syntax for an in-depth understanding

val lambdaName : Type = { argumentList -> codeBody }

Let’s check this code

fun main(args: Array<String>) {val matatu = { println(“33 passengers”)}// invoking functionmatatu()}

Output:

33 passengers

In the code above, a lambda expression is assigned to the immutable variable matatu. Here, the lambda expression doesn’t accept any parameters, and it also does not return any value. It is further invoked as matatu()

Now let’s check a lambda expression that has parameters and a return type.

In the program below, we shall use a lambda expression to take the total tally of a driver and conductor in a matatu (Public Service Vehicle).

33 seater matatu (utimo sacco)

It’ll take the conductor and driver and their types as parameters.

fun main(args: Array<String>) {val matatu = { driver: Int, conductor: Int -> driver + conductor }val result = matatu(1, 1)println(result)}

Output:

2

The lambda expression in the example above is:

{ driver: Int, conductor: Int -> driver + conductor }

the lambda expression is in curly braces

Now with that, you have a slight understanding of Kotlin’s lambda expression in the next part of this article, we shall take an overview of high order functions. Then further master these two concepts in the next series.

If you’ve grasped something from this short article, don’t hesitate to share it for someone else to learn too.

--

--

Matheka Mwanzia
DevCNairobi

Android developer, Entrepreneur, Tech, Politics, Technical Writer (Facebook Developers Circle: Nairobi)