android/kotlin-guides

if else expression

Closed this issue · 2 comments

An if/else conditional that is used as an expression may omit braces only if the entire expression fits on one line.
https://android.github.io/kotlin-guides/style.html#expressions

I propose to relax the rule to allow

val value = if (string.isEmpty())
    calculator.zero() else
    calculator.one()

It's a syntax that I first saw in kotlinx.coroutines and after getting used to it, I found it to be elegant

// https://github.com/Kotlin/kotlinx.coroutines/blob/985f56e54060d05387d25319e630f39e2cce5d5d/js/kotlinx-coroutines-core-js/src/main/kotlin/kotlinx/coroutines/experimental/Deferred.kt#L143-L155
public actual fun <T> async(...): Deferred<T> {
    val newContext = newCoroutineContext(context, parent)

    val coroutine = if (start.isLazy)
        LazyDeferredCoroutine(newContext, block) else
        DeferredCoroutine<T>(newContext, active = true)

    coroutine.initParentJob(newContext[Job])
    start(block, coroutine, coroutine)
    return coroutine
}

Not a big fan of this since it hides the else. It also means that if you need to add an else if you have to significantly change the formatting style.

Understood @JakeWharton, we can close this PR as far as I'm concerned