Is this how you return an empty lambda from an `if...
# getting-started
l
Is this how you return an empty lambda from an
if ... else
expression?
val myLambda: () -> Unit = if (condition) doSomethingLambda else {{}}
j
I would do
else { Unit }
l
Oh, nice
Much more readable, thanks
Other possibility is multiple lines:
Copy code
if (condition) {
    doSomething
} else {
    {}
}
Yeah, it still needs double braces anyway (also in single line...) ☝️
j
I was wrong with earlier reply after misreading it at first. It indeed needs the double braces..
l
Yes, kind of weird...
But I guess that's syntax limitation
j
You could define an empty function somewhere like:
Copy code
fun emptyFunction() {}
And use
Copy code
else ::emptyFunction
That is the only alternative I can think of now
l
I think a lambda is simply an instance of a function type, but don't remember the exact name
This also works, but also doesn't look super readable
Copy code
val myLambda: () -> Unit = if (cond) lambda else fun() {}
j
Or
else fun() = Unit
but still not elegant indeed.
s
I’d use parentheses
Copy code
if (condition) doSomethingLambda else ({})
👍 2
j
Ah yes missed that one!
108 Views