P.Juni
P.Juni

Reputation: 2475

Difference between Unit and { }

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
)

Upvotes: 2

Views: 349

Answers (2)

al3c
al3c

Reputation: 1452

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.

Upvotes: 4

Adam Millerchip
Adam Millerchip

Reputation: 23091

{} 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.

Upvotes: 8

Related Questions