Search code examples
kotlinoopinheritanceinterface

How to implement common properties of the parent interface?


I want to implement common functionality in the parent interface at a single central location. I have:

  • Common Interface: Parent
  • Multiple Child Interfaces: AChild, BChild...

Whenever I try to implement any of these child interfaces, I find myself having to implement properties of the parent interface (Parent) each time, with the implementation being identical across the codebase.

How can I obtain implementations for the child interfaces (AChild, BChild...) without explicitly implementing the parent interface (Parent), under the assumption that the parent interface implementation will be done only once in a central location?

    interface Parent {
        val x: Int
    }
    
    interface AChild : Parent {
        val y: Int
    }
    
    interface BChild : Parent {
        val z: Int
    }
    
    class ASample(value: Int) {
        val aVariable: AChild = object : AChild {
            override val y = value + 20
            override val x = value
        }
    }
    
    class BSample(value: Int) {
        val bVariable: BChild = object : BChild {
            override val z = value + 10
            override val x = value
        }
    }

Solution

  • In order that the parent interface implementation is executed only once in a central location, you can create a delegate as follows:

    class ParentDelegate(value: Int) : Parent {
        override val x: Int = value
    }
    

    And than use it in your implementations for the child interfaces:

    class ASample(value: Int) {
        val aVariable: AChild = object : AChild, Parent by ParentDelegate(value) {
            override val y: Int = value + 20
        }
    }
    
    class BSample(value: Int) {
        val bVariable: BChild = object : BChild, Parent by ParentDelegate(value) {
            override val z = value + 10
        }
    }