简体   繁体   English

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

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

In Kotlin, you can define an abstract function with a default value.在 Kotlin 中,您可以定义一个带有默认值的抽象函数。

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.不仅没有“需要在每个实现中指定相同的默认参数”,甚至是不允许的。

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"

(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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM