Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include logging in Elvis operator?

Tags:

kotlin

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?

like image 488
Dafurman Avatar asked Jul 20 '17 17:07

Dafurman


People also ask

What is Elvis operator and give the representation?

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.

When would you use Elvis operator in Kotlin?

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.

Is there an Elvis operator in Java?

Java has no Elvis operator (or null coalescing operator / null-safe member selection) but with lambda expressions / method references you can roll your own.


1 Answers

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
}
like image 120
hotkey Avatar answered Oct 05 '22 02:10

hotkey