Constraints and Effects

Lambda expressions and anonymous functions can be used interchangeably for the most part. There are two notable differences, though.

Where You Can Supply Anonymous Functions

If a function takes a function type as the last parameter, we can pass a lambda expression outside of the parameter list parentheses:

data class Event(val id: Int)

fun main() {
  val events = listOf(Event(1), Event(5), Event(1337), Event(24601), Event(42), Event(-6))

  val leetEvent = events.first { it.id == 1337 }

  println(leetEvent)
}

Here, first() takes a function type, and we provide a lambda expression outside of the first() call parameter list. Since we have no other parameters on first(), we can even drop the parentheses from the first() call.

We lose those benefits with an anonymous function. We have to provide those inside the parentheses, the way that we would for any other type of parameter:

data class Event(val id: Int)

fun main() {
  val events = listOf(Event(1), Event(5), Event(1337), Event(24601), Event(42), Event(-6))

  val leetEvent = events.first(fun(it: Event): Boolean { return it.id == 1337 })

  println(leetEvent)
}

Where return Returns

A return can be labeled or without a label. A return without a label always returns from whatever function we are in.

An anonymous function is a function, but a lambda expression is not. Hence, the behavior of return is different between the two constructs. A return inside of an anonymous function returns from the anonymous function itself. A return inside of a lambda expression returns from whatever function encloses it.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.