I have a field that needs to be initialized after ...
# announcements
l
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
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
thank you, yes that looks like it will work
d
You can use
check(field == null)
and
checkNotNull(backingField)