Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Defining a Lambda Expression

Consider the following predicate function, which returns true if the given argument is an even integer, false if it is odd:

fun isEven(n: Int): Boolean {
    return n % 2 == 0
}

Because this is so simple, it can be written more compactly, with an expression body. This involves removing the braces, the return statement and the declaration of a return type:

fun isEven(n: Int) = n % 2 == 0

But we can go one step further, and remove the name—turning it into a lambda expression:

{ n: Int -> n % 2 == 0 }

Tasks

  1. Write down a lambda expression that accepts a Double value and returns the square of that value. Use x as the name of expression’s only parameter.

  2. Write down a lambda expression for comparing two Int values named a and b. Your expression should return true if a is less than b, otherwise false.

Solutions

You should have something like this for the first lambda expression:

{ x: Double -> x * x }

The second lambda should look like this:

{ a: Int, b: Int -> a < b }