继承多个接口并同时实现具有相似名称的方法-Kotlin

时间:2020-08-16 12:11:50

标签: kotlin interface overriding multiple-inheritance super

我有以下代码-

package multipleInterfaceDemo

fun main() {
    println(MyClass(val1 = 1, val2 = 2).myFun())
}

private class MyClass(override val val1: Int, override val val2: Int): MyInterface1, MyInterface2 {
    /*override fun myFun() {
        super<MyInterface1>.myFun()
    }*/

    override fun myFun() {
        super<MyInterface2>.myFun()
    }
}

private interface MyInterface1 {
    val val1: Int
    public fun myFun() {
        println(val1)
    }
}

private interface MyInterface2 {
    val val2: Int
    public fun myFun() {
        println(val2)
    }
}

这里我有两个private Interfaces-MyInterface1MyInterface2

每个接口分别具有Int type variable-val1val2,它们在实现{{1}时通过constructors进行设置}

我的Class都有一个名为Interfaces的{​​{1}},它分别打印出methodmyFun()

现在我有一个实现val1val2的类MyClass

MyInterface1有两个MyInterface2参数,用于设置Class实现的两个constructor中的variable

现在两个interfaces的{​​{1}}都具有相似的名称-Class,因此对于Interfaces由{{ 1}}。

在这里,我通过使用method myFun()调用method Interface overriding来清除歧义,并在super之后放置尖括号并放在括号中提到method myFun()类型-superkeyword

现在出现的问题是,我可以覆盖supersuper的{​​{1}}方法。但是我不能同时调用两个Interface的myFun()方法。

那么是否可以进行任何代码调整,以便我可以同时调用MyInterface1MyInterface2的{​​{1}}方法?

已经存在类似的C#问题-

Inheritance from multiple interfaces with the same method name

但是我无法在Kotlin中实现答案

2 个答案:

答案 0 :(得分:3)

不太确定这是您所需要的,但是您可以在同一super<MyInterface1>.myFun()函数中同时使用super<MyInterface2>.myFun()myFun

private class MyClass(override val val1: Int, override val val2: Int): MyInterface1, MyInterface2 {
    override fun myFun() {
        super<MyInterface1>.myFun()
        super<MyInterface2>.myFun()
    }
}

答案 1 :(得分:0)

IR42提供的答案很好,但是以下方法更适合我-

class MyClass() {
    class MyInnerClass1(override val val1: Int): MyInterface1 {
        override fun myFun() {
            super<MyInterface1>.myFun()
        }
    }
    class MyInnerClass2(override val val2: Int): MyInterface2 {
        override fun myFun() {
            super<MyInterface2>.myFun()
        }
    }
}

同时调用两种方法的主函数-

fun main() {
    println(MyClass.MyInnerClass1(val1 = 1).myFun())
    println(MyClass.MyInnerClass2(val2 = 2).myFun())
}