在 Kotlin 中,抽象函数的默认参数值是否继承?
In Kotlin, are default parameter values to abstract functions inherited?
在Kotlin中,您可以定义一个带有默认值的抽象函数。
是否会将此默认值传递给实现函数,而无需在每个实现中指定相同的默认参数?
(It's OK to ask and answer your own questions)
下面的代码确认默认值已传递给实现。
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"
不仅没有"need to specify the same default parameter in each of the implementations",甚至不允许
open class A {
open fun foo(i: Int = 10) { /*...*/ }
}
class B : A() {
override fun foo(i: Int) { /*...*/ } // no default value allowed
}
求评论
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.
另一种选择是使其成为您可以覆盖的方法:
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"
在Kotlin中,您可以定义一个带有默认值的抽象函数。
是否会将此默认值传递给实现函数,而无需在每个实现中指定相同的默认参数?
(It's OK to ask and answer your own questions)
下面的代码确认默认值已传递给实现。
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"
不仅没有"need to specify the same default parameter in each of the implementations",甚至不允许
open class A { open fun foo(i: Int = 10) { /*...*/ } } class B : A() { override fun foo(i: Int) { /*...*/ } // no default value allowed }
求评论
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.
另一种选择是使其成为您可以覆盖的方法:
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"