android/kotlin-guides

Clarify wrapping rules for expression functions

Opened this issue · 1 comments

The guide sets the following guidelines for single-expression functions:

Expression functions should not wrap to two lines. If an expression function grows to require wrapping, use a normal function body, a return declaration, and normal expression wrapping rules instead.

It should be understood that it prohibits the use of this kind of constructs:

fun veryVeryLongFun() = 
        callsAVeryVeryLongFunctionWithHorribleName(andTonsAndTonsOfParameters)

Instead, the following form should be used:

fun veryVeryLongFun() { 
    return callsAVeryVeryLongFunctionWithHorribleName(andTonsAndTonsOfParameters)
}

However, the following expression function, although multiline, doesn't contain wrapping, as it returns a single multiline expression:

fun getFoo(index: Int) = when (index) {
    in 0..10 -> "foo"
    in 11..20 -> "bar"
    else -> "baz"
}

It's easy to misread the style guide and get the impression that expression functions are only valid if they occupy exactly one line. It would be great to have a more clear description of the wrapping rules in this case.

Actually I think we intended to allow

fun veryVeryLongFun() = 
        callsAVeryVeryLongFunctionWithHorribleName(andTonsAndTonsOfParameters)

but prevent

fun veryVeryLongFun() = 
        callsAVeryVeryLongFunctionWithHorribleName(andTonsAndTonsOfParameters,
                 andMoreParameters)

And the multiline one is definitely allowed.

We should include examples as well as wording updates.