Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Unit and { }

Tags:

kotlin

I think I don't understand what is the diff between Unit and {}, e.g. when using callback in a fun.

fun x(
    callback: () -> Unit = {} // fine
)

fun x(
    callback: () -> Unit = Unit // not fine
)
like image 731
P.Juni Avatar asked Jan 22 '26 06:01

P.Juni


2 Answers

{} is a lambda that returns Unit, which is a valid value for () -> Unit.

Unit is an object, which is not a valid value for () -> Unit.

like image 76
Adam Millerchip Avatar answered Jan 26 '26 01:01

Adam Millerchip


Unit is an object with no methods or properties. It's just the default return value for any function. If your function doesn't specify a return type, then that's implicitly returning Unit.

{} is a lambda function that takes no parameters and - since it's the default - returns Unit.

like image 34
al3c Avatar answered Jan 26 '26 01:01

al3c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!