```fun foo() { val a = .. val b = .. val c = .....
# getting-started
u
Copy code
fun 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?
j
it makes sense, but I am not sure if it is better to use
if
for readability tho
e
that only
return 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
Copy code
val a = .. ?: return null
val b = .. ?: return null
val c = .. ?: return null
or
Copy code
if (a == null || b == null || c == null) return null
after which all of
a
,
b
,
c
can be smart-cast to non-null
u
a ?: b ?: c ?: return null
is same as
if (a == null && b == null && c == null)
it's to check if atleast one is not null
so, yes the question is
Copy code
if (a == null && b == null && c == null) return null
vs
Copy code
a ?: b ?: c ?: return null
I'm not sure about the latter, why use expression and then not use the result.. abuse?
k
In Kotlin, many expressions have their results ignored. Take, for instance,
if (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
.
u
I'm not sure why would I use an expression an then ignore the value, when there is if statement