As far as I can see, the only way to use the elvis operator is with syntax like this:
foo = bar ?: return
I was curious if anyone has come up with a way to include logging, as generally the return is used (at least in my experience) when something does not behave as expected.
However, the following syntax is invalid:
foo = bar ?: {
Log.e(TAG, "Some error occurred.")
return
}
Of course I could simply do the following,
foo = bar
if (foo == null) {
Log.e(TAG, "Some error occurred.")
return
}
but is there any way of including logging with the Elvis operator?
The Elvis Operator is represented by a question mark followed by a colon: ?: and it can be used with this syntax: first operand ?: second operand. It enables you to write a consise code, and works as such: If first operand isn't null, then it will be returned. If it is null, then the second operand will be returned.
Elvis operator (?:) is used to return the not null value even the conditional expression is null. It is also used to check the null safety of values. In some cases, we can declare a variable which can hold a null reference.
Java has no Elvis operator (or null coalescing operator / null-safe member selection) but with lambda expressions / method references you can roll your own.
Just use the run { ... }
function from kotlin-stdlib
, which runs the lambda it is passed:
foo = bar ?: run {
Log.e(TAG, "Some error occurred.")
return
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With