I have the following Kotlin class on Android:
class ThisApplication: Application() {
lateinit var network: INetwork
override fun onCreate() {
super.onCreate()
network = Network()
}
}
Now, any external class can get the INetwork reference by simply doing:
application.network
However, that also makes it possible for an external class to overwrite that value:
application.network = myNewNetworkReference
I want to avoid the second option. Unfortunately, I can't make the field val
because its initialization needs to happen inside the onCreate
callback.
I also thought about making the field private and exposing it through a function, like this:
private lateinit var network: INetwork
fun getNetwork() = network
However, whoever calls getNetwork() can still assign a new value to it, like so:
application.getNetwork() = myNewNetworkReference
How can I make the network field to be read-only by external classes? Or even better, is there a way to make it val
even though I can't initialize it inside a constructor?