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

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!

Can yoi use a regular AtomicReference instead?

Yes, you have to write it.

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.

This may spare you from hand-writing the delegation code: java.lang.reflect.Proxy.newProxyInstance()