I have the following code -
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)
}
}
Here I have two private Interfaces - MyInterface1 and MyInterface2
Each interface has an Int type variable - val1 and val2 respectively which are set through constructors in implementing Class
Both my Interfaces have a method called myFun() which prints out val1 and val2 respectively.
Now I have a class MyClass that implements MyInterface1 and MyInterface2.
The Class has two constructor parameters for setting the variable values in the two interfaces implemented by the Class
Now both the Interfaces have a method having similar name - myFun() So there is ambiguity regarding method of which Interface is being implemented by overriding.
Here I clear the ambiguity by calling super method myFun() by using super keyword and after super placing angular brackets and within the brackets mentioning the super Interface type - MyInterface1 or MyInterface2
Now the problem which arises here is that I can override either the myFun() method of Interface1 or of Interface2. But I can't call the myFun() method of both the Interfaces at the same time.
So is it possible to do any code tweak so that I can call myFun() method of both Interface1 and Interface2 at the same time?
A similar C# question already exists -
Inheritance from multiple interfaces with the same method name
But I am unable to implement the answers in Kotlin