Kotlin/kotlin-style-guide

Using lambda as functional parameters

Opened this issue · 1 comments

When making a function with a lambda parameter prefer a simple lambda without a receiver:

// simple lambda:
fun foo(operation: (A) -> Unit) {}

// lambda with receiver (extension-lambda):
fun foo(operation: A.() -> Unit) {}

The reason for this recommendations is that every lambda with a receiver shadows this, which makes the use of nested operations painful.

Cases when a lambda parameter with a receiver is justified:

  • Initialisation
  • Setting a builder object
  • Mutating the receiver inside the operations multiple times
  • The use of scoped operators or infix functions
  • The use of scoped functions for DSL building

I don't think it should be prohibited because there are more cases where it does make sense, but the general idea should be that function types without receiver should be preferred. They are simpler and more intuitive.