"Code in Interfaces" Kotlin,他们如何避免"deadly diamond of death"?

"Code in Interfaces" Kotlin, how do they avoid the "deadly diamond of death"?

我正在阅读 this article and it says that you can write code in Kotlin interfaces. Java did not allow writing code in interface to avoid diamond problem as of this answer。如果 Kotlin 允许接口中的代码并且可以在 class 中实现多个接口,这是否会重新创建 "Diamond Problem"?

场景 1

两个接口具有相同签名的方法,并且都没有在接口中实现,那么它需要实现一个具有相同签名的方法单一方法。

例子

interface InterfaceA {
    fun sum(a: Int, b: Int)
}

interface InterfaceB {
    fun sum(x: Int, y: Int)
}

class TestClass : InterfaceA, InterfaceB {
    override fun sum(x: Int, y: Int) {
       return a+b
   }
}

场景 2

两个接口具有相同签名和不同return类型的方法,在这种情况下会出错

例子

interface InterfaceA {
    fun sum(a: Int, b: Int):Int = a+b
}

interface InterfaceB {
    fun sum(x: Int, y: Int)
}

class TestClass : InterfaceA, InterfaceB {
    override fun sum(x: Int, y: Int) {
       return a+b
   }
}

在这种情况下,编译器会显示错误,因为两种方法必须具有相同的 return 类型

菱形问题与 类 的多重继承有关,这在 Kotlin 和 Java 中都是不允许的,尽管您可以通过实现具有两个接口的接口来创建菱形场景在 kotlin 中,您需要覆盖所有方法,否则会出现编译时错误,从而避免菱形问题。

例子

interface InterfaceA {
    fun sum(a: Int, b: Int): Int {
        print("InterFaceA");
        return a + b
    }
}

interface InterfaceB:InterfaceA {
    override fun sum(a: Int, b: Int): Int {
        print("InterFaceB");
        return a + b
    }
}

interface InterfaceC:InterfaceA {
    override fun sum(a: Int, b: Int): Int {
        print("InterFaceC");
        return a + b
    }
}

interface InterfaceD : InterfaceB, InterfaceC {
    override fun sum(a: Int, b: Int): Int {
        print("InterFaceD");
        return a + b
    }
}

覆盖是必要的,否则编译器将显示错误并且不会继续进行。