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

Alexey Anufriev

08/31/2020, 6:34 PM
hey guys, question about idiomatic syntax what is preferable, this
Copy code
if (event == null) {
    return emptyArray()
}
or this
Copy code
event ?: return emptyArray()
? note: this is just the first line of the method, then comes more logic
1️⃣ 2
n

nanodeath

08/31/2020, 6:36 PM
I like the first a bit because the control flow is more explicit. in the second, you're using the
event
expression as a statement. that is...I think the second would be okay if it the "return value"
event
was used, like in an assignment, but with just what we see here, the first is clearer.
👍 2
s

Shawn

08/31/2020, 6:39 PM
if you’re doing something like this:
Copy code
val event = getEvent()
if (event == null) {
  return emptyArray()
}
then I don’t think it’s unreasonable to shorten it to
Copy code
val event = getEvent() ?: return emptyArray()
👍 8
1
n

nanodeath

08/31/2020, 6:43 PM
on a related note, I'm fine with early returns provided the method is relatively short. if I have to scroll to find all the returns in a method, I'm going to be cranky about it.