Home > database >  Kotlin concrete class extending from abstract class and interface, with the interface using a method
Kotlin concrete class extending from abstract class and interface, with the interface using a method

Time:06-02

I want to ask a question that I have some clues about, but I don't want to influence the answers I will get. I have the following class hierarchy:

abstract class MyAbstractClass { 
    fun displayStuff(id: String) {
        println("My id is $id.")
    }
}

interface MyInterface {
     fun displayThis() {
        displayStuff("some-value")
      }
     fun displayStuff(id: String) // Not implemented here
}

class MyConcreteClass(): MyAbstractClass(), MyInterface {
    fun doStuff() {
        displayThis()
    }
}

fun main() {    
    val result = MyConcreteClass()
    result.doStuff()
    result.displayStuff("id")
}

What's wrong with this design, and how do you suggest I fix it?

CodePudding user response:

It would probably not be a bad idea to extract the displayStuff into another interface. Then MyAbstractClass and MyInterface can both derive from the same interface. One overrides the displayStuff function, hence providing something like an abstract base implementation for the interface. The other one is using the function in a specific way, thereby extending the functionality of the interface.

interface DisplayStuff {
    fun displayStuff(id: String)
}

abstract class MyAbstractClass: DisplayStuff {
    override fun displayStuff(id: String) = println("My id is $id.")
}

interface MyInterface : DisplayStuff {
    fun displayThis() = displayStuff("some-value")
}
  • Related