Reputation: 17307
In the ReKotlin repo README, there is code that looks like this:
data class CounterActionIncrease(val unit: Unit = Unit): Action
What does the code Unit = Unit
do and mean?
Upvotes: 1
Views: 233
Reputation: 45746
The assignment (i.e. Unit = Unit
) in this context is how one defines a default argument. It's no different in concept than if you had:
class Foo(val bar: String = "Default Value")
Since Unit
is an object declaration it's a singleton whose instance is referenced by the object's name. So val unit: Unit = Unit
is assigning the instance of Unit
as the default argument.
That said, it seems strange to have a class property with a type of Unit
. The only reason I can think to do that is because data classes need to declare at least one parameter in the primary constructor, and for some reason the class has no need for "real" properties yet it must be a data class (though I don't understand the need for a data class in this case).
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:
- The primary constructor needs to have at least one parameter; [emphasis added]
- All primary constructor parameters need to be marked as
val
orvar
;- Data classes cannot be abstract, open, sealed or inner;
- (before 1.1) Data classes may only implement interfaces.
Upvotes: 10