3 ms·
In your first example, thats poorly written code that should never make it past code review. I'm also having a hard time thinking of a case where run would even
by Larrikin 4y ago
In your first example, thats poorly written code that should never make it past code review. I'm also having a hard time thinking of a case where run would even be useful in that situation that wouldn't also fix your second example.
If you need all aaa through ddd to be non-null you return early or you check ahead of time
aaa ?: return
bbb ?: return
ccc ?: return
ddd ?: return
or
if (aaa != null && [the rest] != null) foo(aaa, bbb, ccc, ddd)
Since if foo needs them all to be not null they should be passed in
aaa?.bbb?.let{ bbb -> //definitely should not be null in this case
bbb.ccc?.ddd()
} ?: return // or throw an exception
- usrusr 4y agoAnd val aaa = aaa ?: return val bbb = bbb ?: return val ccc = ccc ?: return val ddd = ddd ?: return if those three-letter friends happen to be "getter vals" that might change behind your back (the compiler is perfectly aware of the difference). That's the one gripe I have with kotlin, those "getter vals" that aren't even remotely related to immutability. Likely a consequence of building closely on top of java, there's simply no way an interface could promise to never return two different references from a call on the same object without that promise being a lie. And as usual, kotlin provides gentle damage mitigation on syntax level: "val x = x", as in the four lines above. I would have preferred something even more consise like "val=x" though, where the name overlay is promoted to explicit intention by not typing it twice, as in "call that getter and nail its return to the getter's name for the remainder of our scope". People tend to be reluctant with that name hiding, unsure of it's good style or bad, if there was an explicit shortcut it would be blessed as The Kotlin Way (and, as you said, it's so much better than getting pulled into that let/also nesting abyss that feels clever while writing but turns on you before you are even done)