is there a better way to do early exit from a func...
# announcements
i
is there a better way to do early exit from a function that this?
Copy code
val foo: Foo = optionalFoo ?: run {
    log.e("Not set, can't continue!")
    return
}
g
Copy code
optionalFoo?.let { foo ->
    // body of function
}
// end of function
s
I don’t know if that’s better, seems semantically different and wouldn’t work in many instances where the original snippet would work (e.g. when you have multiple values you need to guard on)
personally speaking I don’t see much wrong with doing away with
optional*
naming and just using
if
to guard —
Copy code
val foo: Foo? = getFooOptional()
if (foo == null)
  log.error("foo not set, can't continue")
  return
}

println(foo.bar)  // can use foo here normally w/o fear of NPE thanks to smart casting
👍 2
m
I would say that's really just taste on how you want to do that. I quite like:
Copy code
val foo = nullableFoo ?: logger.e("message").also { return }
It works for me, as I think there shouldn't be much logic in such a case. In my opinion if that case needs more than one line of code it should be refactored anyways, to keep to code readable.
👍 2
s
readability is not about whether or not logic can fit on one line, it’s about how easily someone unfamiliar with the code can understand what the intent and implementation of the syntax is
👍 2
i
thanks!