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
-
Write down a lambda expression that accepts a
Doublevalue and returns the square of that value. Usexas the name of expression’s only parameter. -
Write down a lambda expression for comparing two
Intvalues namedaandb. Your expression should returntrueifais less thanb, otherwisefalse.