kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

Using lambda as functional parameters

Open voddan opened this issue 9 years ago • 1 comments
trafficstars

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

voddan avatar Jul 08 '16 17:07 voddan

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.

MarcinMoskala avatar Feb 15 '19 15:02 MarcinMoskala