【问题标题】:Is it possible to satisfy an interface member implementation using another interface in Kotlin?是否可以使用 Kotlin 中的另一个接口来满足接口成员实现?
【发布时间】:2019-07-04 07:53:32
【问题描述】:

例如,如果我有这样的界面:

interface MyInterface {
    fun thouMustImplementThis()
}

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

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

我不想要这个。

重点是,我想为一些原生接口创建某种默认实现,这样我就不必在每次基于这些接口创建类时都重新实现它们。我在想,通过将其作为接口,我可以根据需要“附加”实现。有什么解决方法吗?

【问题讨论】:

    标签: class kotlin interface


    【解决方案1】:

    您可以让该接口实现另一个接口。 像这样:

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

    现在,类可以这样实现(不需要主体):

    class MyClass : View, YourInterface
    

    【讨论】:

    • 哦,这在我的想法中从未发生过。谢谢!!
    猜你喜欢
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多