gpt4 book ai didi

kotlin - 在 Kotlin 中,抽象函数的默认参数值是否继承?

转载 作者:行者123 更新时间:2023-12-02 13:01:55 25 4
gpt4 key购买 nike

在 Kotlin 中,您可以定义具有默认值的抽象函数。

是否会将该默认值传递给实现函数,而无需在每个实现中指定相同的默认参数?

最佳答案

不仅没有“需要在每个实现中指定相同的默认参数”,甚至不允许。

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
}

评论

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 - 在 Kotlin 中,抽象函数的默认参数值是否继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60634507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com