https://kotlinlang.org logo
#announcements
Title
# announcements
n

Nikolay Kasyanov

07/04/2019, 3:05 PM
hey folks, is this a known issue/feature?
Copy code
kotlin
fun main(args: Array<String>) {
    whatever(-2)
    whatever(0)
    whatever(2)
}

fun whatever(input: Int) {
    if (input < 0) {
        "negative"
    } else if (input > 0) {
        "positive"
    } else {
        "zero"
    }.let {
        println(it)
    }
}
prints:
Copy code
zero
positive
r

robstoll

07/04/2019, 3:09 PM
that's normal behaviour, intellij even suggest that you can replace the let statement and instead write:
Copy code
if (input < 0) {
        "negative"
    } else println(
        if (input > 0) {
            "positive"
        } else {
            "zero"
        }
    )
you could write the following if you want the
let
:
Copy code
(if (input < 0) {
        "negative"
    } else if (input > 0) {
        "positive"
    } else {
        "zero"
    }).let {
        println(it)
    }
your code is the same as :
Copy code
if (input < 0) {
        "negative"
    } else {
        (if (input > 0) {
            "positive"
        } else {
            "zero"
        }).let {
            println(it)
        }
    }
n

Nikolay Kasyanov

07/04/2019, 3:11 PM
I see, so let “binds” to the latest
if-else
subexpression?
r

robstoll

07/04/2019, 3:12 PM
exactly
n

Nikolay Kasyanov

07/04/2019, 3:12 PM
@robstoll thank you!
p

pivovarit

07/04/2019, 3:13 PM
also, the best way to deal with such cascading logic is to use
when
Copy code
when {
  input < 0 -> "negative"
  input > 0 -> "positive"
  else -> "zero"
}
👍 6
1
n

Nikolay Kasyanov

07/04/2019, 3:17 PM
this
let
behaviour still feels counterintuitive though 😅
s

SiebelsTim

07/04/2019, 4:27 PM
It's not let specifically. else if is just an else branch with an if inside of it.
l

louiscad

07/04/2019, 5:29 PM
Using an extension on an
else
expression without parentheses is not good for readability IMHO
4
r

ribesg

07/04/2019, 7:35 PM
else if
is not
elif
for a reason 🙂