Search code examples
androidkotlin

Kotlin, Implementing two interfaces with same method and have default values


Let's say I have Two interfaces with same method name and signature and have default value for its parameter, implemented by a single class there will be a compilation error:

More than one overridden descriptor declares a default value for 'value-parameter b: Boolean = ... As the compiler can not make sure these values agree, this is not allowed.

Ex:

    interface A {
    fun f(b: Boolean = true)
    }

    interface B {
    fun f(b: Boolean = false)
    }

    class C : A, B {

    override fun f(b: Boolean) {

      }
   }

Is there a way to solve this issue or should I define two different methods


Solution

  • You can not do this. because the implementor method can not have a default value. and if you use C().f() how the compiler is going to know use which default value? because C() is An A and it is Also a B.

    C().f() has to call C.f(true) because true is the default value in A. and C().f() also has to call C().f(false) because false is default value in B. so it is a conflict and it is not allowed.

    You can do something like this to achieve what you want :

    interface A {
    fun f(b)
    fun f(){f(true)}
    }
    
    interface B {
    fun f(b)
    fun f(){f(false)}
    }
    
    class C : A, B {
    
    override fun f(b: Boolean) {
    
    }
    override fun f() {
    // now you can define which default value is used for class C 
    // You can define either true or false
    f(true)
    }
    
    }