Thursday, 11 January 2018

Kotlin: Overriding conflict while implementing interfaces

If you are implementing more than one interface and those interfaces have same method signatures, then you will end up in conflict scenario.

HelloWorld.kt
interface Interface1{
 fun welcomeMessage(name : String){
  println("Welcome $name")
 }
}

interface Interface2{
 fun welcomeMessage(name : String){
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2{

 
}

When you try to compile above program, you will end up in below error.

ERROR: Class 'MyClass' must override public open fun welcomeMessage(name: String): Unit defined in Interface1 because it inherits multiple interface methods of it (13, 1)

How to resolve above error?
By overriding the function welcomeMessage in MyClass, you can get rid of above error.

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  println("Hello $name")
 }

}

Find the below working application.


HelloWorld.kt
interface Interface1 {
 fun welcomeMessage(name: String) {
  println("Welcome $name")
 }
}

interface Interface2 {
 fun welcomeMessage(name: String) {
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  println("Hello $name")
 }

}

fun main(args: Array<String>) {
 var obj = MyClass()
 obj.welcomeMessage("krishna")
}

Output
Hello Krishna

How can I call interface method implementations from class?
By using super keyword, you can call interface method implementations from a class.

Ex
class MyClass : Interface1, Interface2 {
         override fun welcomeMessage(name: String) {
                 super<Interface1>.welcomeMessage(name)
                 super<Interface2>.welcomeMessage(name)
         }
}

Find the below working application.

HelloWorld.kt

interface Interface1 {
 fun welcomeMessage(name: String) {
  println("Welcome $name")
 }
}

interface Interface2 {
 fun welcomeMessage(name: String) {
  println("Good Morning $name")
 }
}

class MyClass : Interface1, Interface2 {
 override fun welcomeMessage(name: String) {
  super<Interface1>.welcomeMessage(name)
  super<Interface2>.welcomeMessage(name)
 }
}

fun main(args: Array<String>) {
 var obj = MyClass()
 obj.welcomeMessage("krishna")
}

Output

Welcome krishna
Good Morning Krishna


Previous                                                 Next                                                 Home

No comments:

Post a Comment