ursus
12/17/2024, 10:41 PMfun foo() {
val a = ..
val b = ..
val c = ..
a ?: b ?: c ?: return null
...
}
does this code make sense? i.e. using elvis without using the result?Javier
12/17/2024, 10:52 PMif
for readability thoephemient
12/17/2024, 11:14 PMreturn null
if all of a
, b
, c
are null. if that's what you want, great.
if what you actually want is to return null
unless all of a
, b
, c
are non-null (which I believe is a more common check to make), then you should either
val a = .. ?: return null
val b = .. ?: return null
val c = .. ?: return null
or
if (a == null || b == null || c == null) return null
after which all of a
, b
, c
can be smart-cast to non-nullursus
12/17/2024, 11:23 PMa ?: b ?: c ?: return null
is same as if (a == null && b == null && c == null)
it's to check if atleast one is not nullursus
12/17/2024, 11:25 PMif (a == null && b == null && c == null) return null
vs
a ?: b ?: c ?: return null
I'm not sure about the latter, why use expression and then not use the result..
abuse?Klitos Kyriacou
12/18/2024, 10:59 AMif (cond) doSomething() else return null
. That's an expression (even if doSomething()
returns Unit
) but we have no qualms about ignoring its return value. Given this, I have no problem with a ?: return null
as a succinct alternative to if (a == null) return null
. However, I do have a problem with a ?: b ?: c ?: return null
because it's not immediately obvious whether it's checking for all or any null value. It only takes me a couple of seconds to realize which one it is, but a couple of seconds is enough to interrupt my train of thought. Furthermore, if you're checking if any value is non-null, then in most cases you'd want to make use of at least one such non-null value, so why not assign that non-null value to a variable anyway? So I'd use val firstNonNull = a ?: b ?: c ?: return null
.ursus
12/18/2024, 11:07 AM