https://kotlinlang.org logo
a

aleksey.tomin

12/23/2020, 4:28 PM
Is it a bug? On this code
Copy code
memScoped {
        if (...) {
            value?.let { callVoidFunction1() }
        } else if (..) {
            callVoidFunction1()
        }
    }
I have error on IDEA:
'if' must have both main and 'else' branches if used as an expression
I can fix it by add
} else {
at end but it looks like ugly.
r

Russell Stewart

12/23/2020, 4:29 PM
I've seen that sort of thing before in other situations, and it always confuses me. I don't know if it's a bug in IDEA, or some weird quirk in how Kotlin parses that
if/then
statement. Either way, it's definitely non-intuitive. One suggestion: instead of an empty
else
statement, you could do this:
Copy code
memScoped {
        if (...) {
            value?.let { callVoidFunction1() }
        } else {
          if (..) {
            callVoidFunction1()
          }
        }
    }
Still a little clumsy, but not quite as ugly as having an empty
else
hanging around.
e

ephemient

12/23/2020, 5:03 PM
or you could put anything after the
if
, so that it's not being used like a value
Copy code
memScoped {
    if (...) { ... }
    Unit
}
👍 1
r

rharter

12/23/2020, 5:58 PM
It's not a bug, it happens because
memScoped
has a return value and lamdas that return values automatically treat the last expression as a return, so the
if
is being treated as an expression (like
val foo = if ...
). As @ephemient mentioned, you could add anything after to be treated as the return instead, or put the conditional in a
run
block, or anything else that makes it clear that the if is not an expression to be returned.
a

Animesh Sahu

12/24/2020, 5:14 AM
You can
memScoped<Unit> {
4 Views