https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

02/12/2023, 12:06 PM
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

Adam S

02/12/2023, 12:07 PM
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

y

02/12/2023, 12:11 PM
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

Adam S

02/12/2023, 12:11 PM
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

y

02/12/2023, 12:12 PM
okay. thanks for digging up that issue. seems like it’s either intended behavior or at the very least not a priority
a

Adam S

02/12/2023, 12:14 PM
the empty
else {}
isn’t necessary if the function has a block body
Copy code
fun returnsUnit() {
  if (condition) {
    doSomething
  }
}
e

ephemient

02/12/2023, 12:50 PM
it isn't necessary in a Unit-returning lambda either
s

Stephan Schröder

02/12/2023, 4:21 PM
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

ephemient

02/12/2023, 4:32 PM
right. all expressions can be statements, but not all statements are expressions. declarations, loops, and non-exhaustive
when
are also not expressions
y

y

02/12/2023, 4:52 PM
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

ephemient

02/14/2023, 7:52 AM
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.
6 Views