`fun returnsUnit() = if (condition) { doSomething ...
# getting-started
y
fun returnsUnit() = if (condition) { doSomething }
…does not compile, but
fun returnsUnit() = if (condition) { doSomething } else { }
does. I understand why it is like this, but is this considered a bug?
a
https://kotlinlang.org/docs/control-flow.html#if-expression
If you’re using
if
as an expression, for example, for returning its value or assigning it to a variable, the
else
branch is mandatory.
4
y
I understand why it is like this, but some languages (Rust is one I know of) do allow this for
Unit
return values (by implicitly adding a
else { return Unit }
)
a
this is the closest feature request I could find https://youtrack.jetbrains.com/issue/KT-18694
understood - but it’s intended behaviour, not a bug
y
okay. thanks for digging up that issue. seems like it’s either intended behavior or at the very least not a priority
a
the empty
else {}
isn’t necessary if the function has a block body
Copy code
fun returnsUnit() {
  if (condition) {
    doSomething
  }
}
e
it isn't necessary in a Unit-returning lambda either
s
I always assumed that an if branch without an else branch is simply a statement and not an expression!? The reason it works at the end of a lambda or function returning Unit is that both get a
return Unit
implicitly added to it anyway. At least that is my mental model which seems to comply with actual behaviour (compiler implementation may differ).
e
right. all expressions can be statements, but not all statements are expressions. declarations, loops, and non-exhaustive
when
are also not expressions
y
now that I understand the degree to which Kotlin is “expression-oriented” I guess the if-without-else here is not necessarily an inconsistency. not when something like non-exhaustive
when
is allowed by the compiler.
e
to a degree, Rust started life as OCaml with C-like syntax, while Kotlin started life as Java improved. so while modern language design has converged in some ways, the expression/statement divide is one of those that is still a bit different.