Alexey Subbota
Alexey Subbota

Reputation: 972

How to use temporary object that is passed to super constructor?

interface I

open class Base(protected val i: I)

class Impl: I
class Derived(args:Bundle): Base( Impl(args) ) { // here I create an instance of Impl
    private val my: Impl // See my question 
}

My Base class depends on an interface I. But the implementation Impl is created in Derived class. I want to use Impl object in Derived class too. I can see the Base implementation and cast super.i to Impl but I don't want to depends on Base's implementation details. Can I store Impl somewhere to restore in to Derived.my member? I have a restriction from the library: a class has to have a constructor with args:Bundle argument, no more or less

Upvotes: 0

Views: 108

Answers (1)

Tenfour04
Tenfour04

Reputation: 93571

If you are opposed to simply casting the superclass's property i as Impl, you could do this using a secondary constructor and making your primary constructor private:

class Derived private constructor(private val my: Impl): Base(my) {

    constructor(args: Bundle): this(Impl(args))

}

Upvotes: 3

Related Questions