https://kotlinlang.org logo
Title
c

Camshaft54

12/12/2021, 4:54 PM
I have a question regarding elvis operators. If I want to print something then return from a function if the value is null, how would I do that with an elvis operator? I tried to do this, but I get an error saying that return is not allowed here:
// getVal() returns a nullable value
fun example() {
    val myVal = getVal() ?: {
        println("value is null")
        return
    }
}
j

Joffrey

12/12/2021, 4:56 PM
This is because
{ ... }
is not considered as a block of code here, but as a lambda. You might want to try
run { ... }
instead
c

Camshaft54

12/12/2021, 4:57 PM
Ah I see, that makes sense. Thanks!
y

Youssef Shoaib [MOD]

12/12/2021, 5:00 PM
Run blocks are quite a useful Kotlin idiom, so trust me this won't be the last time you see them. I'd encourage you to, of course, take a look at the scoping functions documentation
👍 4
😁 1
f

Francesc

12/12/2021, 7:22 PM
For this particular case, as you have a side effect, consider using
also
j

Joffrey

12/12/2021, 11:33 PM
@Francesc how would you use
also
here? The idea is to print when the expression is null, not when it's not null. Using
getVal()?.also { ... }
would do the opposite. So I guess elvis + run block is the way to go here.