是否可以使用Kotlin中的另一个接口来满足接口成员实现



例如,如果我有这样的接口:

interface MyInterface {
    fun thouMustImplementThis()
}

我有一个MyClass类,该类实现MyInterface,这意味着我必须为该功能创建一个覆盖:

class MyClass : View, MyInterface {
    override fun thouMustImplementThis() {
        println ("Hello world")
    }
}

如果我有另一个实现该函数的接口:

interface YourInterface {
    fun thouMustImplementThis() {
        println ("Hello Stack Overflow")
    }
}

所以我可以将实施删除:

class MyClass : View, MyInterface, YourInterface {
}

,但我发现我仍然必须实现该功能,尽管我只需要在其超级功能版本中添加一个呼叫。

class MyClass : View, MyInterface, YourInterface {
    override fun thouMustImplementThis() {
        super.thouMustImplementThis()
    }
}

我不想要这个。

重点是,我想为某些本机接口创建某种默认实现,以便每次我基于这些接口创建类时都不必重新成真。我认为,通过将其作为接口,我可以根据需要"附加"实现。有什么解决方法吗?

您只能让接口实现另一个接口。这样:

interface YourInterface : MyInterface {
    override fun thouMustImplementThis() {
        println("Hello Stack Overflow")
    }
}

现在,可以这样实现该类(不需要身体(:

class MyClass : View, YourInterface

最新更新