https://kotlinlang.org logo
#announcements
Title
# announcements
l

Luis Munoz

08/28/2019, 3:22 PM
I have a field that needs to be initialized after the object is created and then never modified, is there way to make it immutable so that it can be read concurrently after initialized
b

Burkhard

08/28/2019, 3:41 PM
Something like this could work
Copy code
private var backingField: Foo? = null
    set(value) {
         if(field == null) field = value
         else throw IllegalStateException("field already initialized")
    }
val property: Foo
    get() = backingField ?: throw IllegalStateException("field not initialized")
If the field needs to be nullable you can make the backing property of type
Any?
and create a dummy singleton object that represents the absence of a value. In the normal property just add a cast to the right type.
Also you can extract all that into a delegate. That way it’s easier to reuse.
l

Luis Munoz

08/28/2019, 4:06 PM
thank you, yes that looks like it will work
d

Dico

08/28/2019, 4:34 PM
You can use
check(field == null)
and
checkNotNull(backingField)
3 Views