Is it possible to use the delegation pattern with a nullable type?


#1

I have an interface:

interface Foo {
    fun doSomething()
}

I have several classes that implement this interface. I also have a class, FooWrapper:

class FooWrapper(var delegate: FooImpl?) : Foo by delegate // doesn't work

Is it possible to use a nullable type there? Basically, I want to retain an instance of FooWrapper forever as a singleton, but switch out its delegate based on certain events, for magical Android reasons. Without this, I have to hand-write the delegation code.

Thanks!


#2

Can yoi use a regular AtomicReference instead?

Yes, you have to write it.


#3

I did consider using an AtommicReference, but now I’m not sure why I forgot about that idea. Thanks for the thought – I’ll take a look.