How can I acces function from Delegate that I overrite


#1

Let’s assume I have the following Interface and classes:

interface MyAwesomeInterface {
    fun getNumber(): Int
    fun otherFunction()
}

class MyAwesomeInterfaceImpl: MyAwesomeInterface {
    override fun otherFunction() {
        println("Something awesome!")
    }

    override fun getNumber(): Int {
        return 1
    }
}

class MyAwesomeClass(): MyAwesomeInterface by MyAwesomeInterfaceImpl() {
    override fun getNumber(): Int = 10
}

How Could I get acces to the getNumber() function from MyAwesomeInterfaceImpl in MyAwesomeClass()?


#2

Make MyAwesomeInterfaceImpl instance a variable.
Rough sketch:

class AwesomeClass(): AwesomeInterface by interfaceImpl {
      private val interfaceImpl = MyAwesomeInterfaceImpl()
  
      fun someFunction() {
           println(interfaceImpl.getNumber())
      }
}

#3

That gives me a Compiler error:

Error:(18, 47) Kotlin: Unresolved reference: myAwesomeImpl


#4

Perhaps this will work?

class AwesomeClass private constructor(private val impl: MyAwesomeInterfaceImpl): AwesomeInterface by impl {
      constructor() : this(MyAwesomeInterfaceImpl())
  
      fun someFunction() {
           println(impl.getNumber())
      }
}