16 Application Singleton and Delegated Properties
57
The problem with Android is that we don’t have control over many class constructors. For instance,
we cannot initialise a non-nullable property, because its value needs to be defined in the constructor.
So we need a nullable variable and then a function that returns a non-nullable value. We know we
always have an
App
instance, and that nothing under our control can be done before application
onCreate
, so we are safe by assuming
instance()
function will always be able to return a non-
nullable
App
instance.
But this solution seems a bit unnatural. We need to define a property (which already has a getter
and a setter) and then a function to return that property. Do we have another way to get a similar
result? Yeah, we can delegate the value of a property to another class. This is commonly know as
Do'stlaringiz bilan baham: