hey folks, is this a known issue/feature? ```kotl...
# announcements
n
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
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
I see, so let “binds” to the latest
if-else
subexpression?
r
exactly
n
@robstoll thank you!
p
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
this
let
behaviour still feels counterintuitive though 😅
s
It's not let specifically. else if is just an else branch with an if inside of it.
l
Using an extension on an
else
expression without parentheses is not good for readability IMHO
4
r
else if
is not
elif
for a reason 🙂