hho
02/02/2022, 11:16 AMreturn
even if some branches don't return anything? I think I might like the version with multiple return statements better in this case…
return if (someExpr) {
doSomeStuff()
someThing
} else if (otherExpr) {
doOtherStuff()
otherThing
} else {
throw RuntimeException("uh oh")
}
Joffrey
02/02/2022, 11:18 AMreturn
out of the if
when I have one-liners in every branch. I would also likely make it a when
because I think they look better as expressions than if
when the whole if
doesn't fit on a single line (especially if there are more than 2 branches)Joffrey
02/02/2022, 11:19 AMwhen
expression into its own function so there is not even one return
anymoreJoffrey
02/02/2022, 11:22 AMreturn theWhenStuff()
With the following extra declarations:
fun theWhenStuff() = when {
someExpr -> doSomeStuffThatReturnsSomeThing()
otherExpr -> doSomeOtherStuffThatReturnOtherThing()
else -> error("uh oh")
}
fun doSomeStuffThatReturnsSomeThing() {
doSomeStuff()
return someThing
}
fun doSomeOtherStuffThatReturnOtherThing() {
doOtherStuff()
return otherThing
}
Joffrey
02/02/2022, 11:25 AMeven if some branches don't return anythingSo your problem is with the
throw
there? That doesn't bother me. Throw returns Nothing
which makes the whole thing clean IMOhho
02/02/2022, 11:28 AMJoffrey
02/02/2022, 11:40 AMval x = something ?: throw SomeException("blah")
// or
return something ?: throw SomeException("blah")
Although I have to admit this last part itches a tiny little bit. It would depend on context I guessJon Senchyna
08/11/2022, 2:11 PMif
to when
there. With the way the two are naturally indented, the when
statement does a much better job of visually associating all of the branches back to the return
.