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?
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?
Not only there's no "need to specify the same default parameter in each of the implementations", it isn't even allowed.
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"
(It's OK to ask and answer your own questions)
The code below confirms that the default value is passed to the implementation.
interface IParent {
fun printSomething(argument: String = "default") // default val specified in interface
}
class Child : IParent {
override fun printSomething(argument: String){ // no default val specified in impl.
println(argument)
}
}
Child().printSomething() // compiles successfully, and prints "default"