I have a question regarding elvis operators. If I ...
# getting-started
c
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:
Copy code
// getVal() returns a nullable value
fun example() {
    val myVal = getVal() ?: {
        println("value is null")
        return
    }
}
j
This is because
{ ... }
is not considered as a block of code here, but as a lambda. You might want to try
run { ... }
instead
c
Ah I see, that makes sense. Thanks!
y
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
For this particular case, as you have a side effect, consider using
also
j
@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.