Kotlin - How to make field read-only for external classes -


i have following kotlin class on android:

class thisapplication: application() {      lateinit var network: inetwork      override fun oncreate() {          super.oncreate()          network = network()     } } 

now, external class can inetwork reference doing:

application.network 

however, makes possible external class overwrite value:

application.network = mynewnetworkreference 

i want avoid second option. unfortunately, can't make field val because initialization needs happen inside oncreate callback.

i thought making field private , exposing through function, this:

private lateinit var network: inetwork fun getnetwork() = network 

however, whoever calls getnetwork() can still assign new value it, so:

application.getnetwork() = mynewnetworkreference 

how can make network field read-only external classes? or better, there way make val though can't initialize inside constructor?

to restrict access external classes, can change visibility of accessors. case, need private setter , public getter lateinit modifier:

lateinit var network: inetwork     private set 

or read-only lazy property:

val network: inetwork lazy { network() }  //you can access private property here, eg. applicationcontext 

there misunderstanding code:

private lateinit var network: inetwork fun getnetwork() = network 

kotlin pass-by-value java does. so, application.getnetwork() = mynewnetworkreference not valid statement. cannot assign value return value of function.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -