Enable logging in an Elvis statement?

As far as I can see, the only way to use the elvis operator is the syntax:

foo = bar ?: return 

I was curious if anyone had come up with a way to enable logging, since returns are usually used (at least in my experience) when something doesn't behave as expected.

However, the following syntax is invalid:

 foo = bar ?: { Log.e(TAG, "Some error occurred.") return } 

Of course, I could just do the following:

 foo = bar if (foo == null) { Log.e(TAG, "Some error occurred.") return } 

but is there a way to enable logging using the Elvis operator?

+5
source share
3 answers

Just use the run { ... } function from kotlin-stdlib , which runs the passed lambda:

 foo = bar ?: run { Log.e(TAG, "Some error occurred.") return } 
+5
source

{} is a lambda, you should call it, for example:

 // v--- it is a lambda foo = bar ?: return { Log.e(TAG, "Some error occurred.") }() // <--- invoke the lambda 

OR call lambda with let :

 foo = bar ?: return let{ Log.e(TAG, "Some error occurred.") } 
+2
source

Oh, all you have to do is the following:

 foo = bar ?: kotlin.run { Log.e(TAG, "Some error occurred.") return } 

It may be perhaps less readable than the standard if the zero check, but at least here how you do it.

+1
source

Source: https://habr.com/ru/post/1270029/


All Articles