can anyone think of a more idiomatic way to do this?
Copy code
if (error != null) throw error
c
Casey Brooks
05/15/2020, 5:33 PM
not much different, but you can do
error?.let { throw it }
➖ 1
😄 1
➕ 2
j
jw
05/15/2020, 6:06 PM
It is already idiomatic. Anything else you do will be either trying to be clever or code golfing character count. Or both.
👍 2
k
Kevin Gorham
05/15/2020, 8:47 PM
Good point. I think it's just the mechanics of
throw
that make this feel more awkward than other, similar code. Parameters that are exceptions are often nullable. I almost wish that
throw null
did nothing or
error?.throw
worked.
I'm fine writing the lengthier version, I just had a suspicion that there might be some other stdlib approach out there that I didn't know about.
a
Arkadii Ivanov
05/16/2020, 12:23 AM
You can always define your own extension function. But again, this is already ideomatic.
d
Derek Peirce
05/16/2020, 3:11 AM
If
throw null
worked, then everywhere a
throw e
occured, I would have to double-check that
e
is non-null, or else it isn't a guaranteed throw and the remaining code in that block might still happen.
j
jw
05/16/2020, 3:45 PM
throw null
works in Java and in Java bytecode as an easy way to throw an NPE