Kotlin / kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
288 stars 14 forks source link

Using lambda as functional parameters #29

Open voddan opened 8 years ago

voddan commented 8 years ago

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:

MarcinMoskala commented 5 years ago

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.