https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lukasz Kalnik

07/22/2022, 11:53 AM
Is this how you return an empty lambda from an
if ... else
expression?
val myLambda: () -> Unit = if (condition) doSomethingLambda else {{}}
j

Jurriaan Mous

07/22/2022, 11:54 AM
I would do
else { Unit }
l

Lukasz Kalnik

07/22/2022, 11:55 AM
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

Jurriaan Mous

07/22/2022, 12:00 PM
I was wrong with earlier reply after misreading it at first. It indeed needs the double braces..
l

Lukasz Kalnik

07/22/2022, 12:01 PM
Yes, kind of weird...
But I guess that's syntax limitation
j

Jurriaan Mous

07/22/2022, 12:02 PM
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

Lukasz Kalnik

07/22/2022, 12:02 PM
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

Jurriaan Mous

07/22/2022, 12:09 PM
Or
else fun() = Unit
but still not elegant indeed.
s

Sam

07/22/2022, 12:45 PM
I’d use parentheses
Copy code
if (condition) doSomethingLambda else ({})
👍 2
j

Jurriaan Mous

07/22/2022, 12:49 PM
Ah yes missed that one!
6 Views