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

Inheriting multiple Interfaces and implementing methods with similar names at the same time - Kotlin

我有以下代码-

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 分别通过 constructors 在实现 Class

我的 Interfaces 都有一个名为 myFun()method,它分别打印出 val1val2

现在我有一个 class MyClass 实现了 MyInterface1MyInterface2

Class有两个constructor参数,用于设置Class

实现的两个interfaces中的variable

现在 Interfaces 都有一个具有相似名称的 method - myFun() 因此关于 methodInterface 正在实施中存在歧义overriding.

这里我通过使用super keyword 调用super method myFun() 并在super 之后放置[=85 来消除歧义=] 括号内并在括号内提及 super Interface 类型 - MyInterface1MyInterface2

现在这里出现的问题是我可以覆盖 Interface1Interface2myFun() 方法。但是我不能同时调用 Interfaces 的 myFun() 方法。

那么是否可以进行任何代码调整,以便我可以同时调用 Interface1Interface2myFun() 方法?

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

Inheritance from multiple interfaces with the same method name

但我无法在 Kotlin 中实现答案

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

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

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