I was reading 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. If Kotlin allows code in interface and multiple interfaces can be implemented in a class, doesn't this create the "Diamond Problem" all over again?
1 Answer
Scenario 1
Two interfaces have methods with same signature and both don't have implementation in interface then it need to implement a method single method with same signature.
Example
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
}
}
Scenario 2
Two interfaces have methods with same signature and different return type will be an error in this case
Example
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
}
}
In this case compiler show error because both method must have same return type
The diamond problem is associated with multiple inheritance of classes that is not allowed in Kotlin as well as Java though you can create a scenario of diamond shape by implementing an interface with two interfaces then in kotlin you need to override all of methods otherwise it is a compile time error and this avoid diamond shape problem.
Example
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
}
}
override is necessary otherwise compiler will show an error and won't proceed further.
Java did not allow writing code in interface
It does: docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html