Resolving conflicts between interfaces

As we know, a class can implement more than one interface. What happens if two interfaces have the same signatures; how can we choose one of these functions? To understand this concept, we need to create another interface called IFlyable with two functions—fly and engineStart. We can implement the engineStart function and define the fly function as follows:

interface IFlyable {
fun startEngine(){
println("Jet engine is ready ...")
}
fun fly()
}

Let the Car class implement the IFlyable interface to create an advanced vehicle that can drive and fly:

class Car(override var numberOfDoors: Int, val name : String) : IDriveable, IFlyable {

override fun startEngine() {

}

override fun fly() {
println("$name is ready to fly...")
}

override fun moveForward() {
println("$name is driving on the road")
}
}

The IFlyable and IDriveable interfaces contain a function called startEngine. In the Car class, there is no conflict for the startEngine function, as long as we want to provide our own implementation. When we try to use a function from one of the interfaces, however, it will look as follows:

override fun startEngine() {
super.startEngine()
}

Kotlin will throw the following error:

Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super<Foo>'

We need to call the function by explicitly providing the interface name with the super keyword:

override fun startEngine() {
super<IDriveable>.startEngine()
}

 By using the super keyword and the diamond operator, Kotlin knows which function to call.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.12