Home > Blockchain >  How to use temporary object that is passed to super constructor?
How to use temporary object that is passed to super constructor?

Time:02-11

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

CodePudding user response:

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))

}
  • Related