Search code examples
kotlinmethodsdefault-valueabstraction

In Kotlin, are default parameter values to abstract functions inherited?


In Kotlin, you can define an abstract function with a default value.

Will this default value will be carried over to the implementing functions, without the need to specify the same default parameter in each of the implementations?


Solution

  • Not only there's no "need to specify the same default parameter in each of the implementations", it isn't even allowed.

    Overriding methods always use the same default parameter values as the base method. When overriding a method with default parameter values, the default parameter values must be omitted from the signature:

    open class A {
    
        open fun foo(i: Int = 10) { /*...*/ }
    }
    
    class B : A() {
    
        override fun foo(i: Int) { /*...*/ }  // no default value allowed
    }
    

    For the comment

    I guess if we wanted a different default value for the implementing classes, we would need to either omit it from the parent or deal with it inside the method.

    Another option is to make it a method which you can override:

    interface IParent {
        fun printSomething(argument: String = defaultArgument())
        
        fun defaultArgument(): String = "default"
    }
    
    class Child : IParent {
        override fun printSomething(argument: String) {
            println(argument)
        }
    
        override fun defaultArgument(): String = "child default"
    }
    
    Child().printSomething() // prints "child default"