IMO the elvis operator adds “convenience” both on the writing side AND the reading side. The expressions with elvis look specific and have their specific behaviour, so I (personally) never had any occurrence where I found it misleading or was surprised in any way.
I believe the feature suggested here is different in this respect. I find this tiny extra ?
character easy to miss, partly because it looks like other things in the syntax. Also, it behaves differently, especially in the sense that ?
-based expressions usually don’t impact a wider scope than the expression itself. For instance I find the following code pretty misleading, especially if variable names are real-life multi-letter names:
val r1 = someFunction(a, b, c)
val r2 = someFunction(a, b?, c)
val r3 = someFunction(a, b?.prop, c)
val r4 = someFunction(a, b?.prop?, c)
Kotlin aims at being concise, but strives for explicitness, and even though there is a difference between b
, b?
, b?.prop
, and b?.prop?
, I don’t think this syntax makes it obvious to the reader in one glance which of these calls could actually be skipped.
We could make the same case against using the elvis + return
in a function call, by the way:
val result = someFunction(a, b ?: return 42, c)
I would much rather have an intermediate variable here. But at least, the return
keyword stands out. I find the use of elvis + return
convenient in other places but a bit dangerous here. The proposed syntax however only concerns function parameters, and this place IMO is dangerous for readability. Maybe it’s just a matter of habits.