正如标题中所述:为什么可以忽略子类型的重写成员函数中的默认值?

Is this normal or to be expected?

interface Foo {
  fun bar(parameter: Int = 1)
}

class Baz : Foo {
  override fun bar(parameter: Int) { // OK
    println(parameter)
  }
}

val baz = Baz()

baz.bar() // OK
baz.bar(2) // OK

Same behavior in the case where Foo is a class.

推荐答案

这是正常的还是意料之中的?

I suspect this was primarily a language design / usability decision. From this perspective, there were four options available:

  1. Declare in supertype only.
  2. Declare in subtype only.
  3. 在两者中声明,但不允许子类型更改默认值.
  4. 在两者中声明,允许子类型覆盖父类型中的默认值.

The Kotlin designers chose option #1. This makes sense because:

选项#2和#4都暗示调用者不知道默认值是什么,除非他们知道自己使用的是哪个实现,这当然是非常不可取的.调用方需要额外的逻辑来确定是否需要一个值来覆盖默认值,这意味着默认值将是无用的.

选项3违反了DRY principle.为什么要把声明放在两个地方?

That leaves Option #1 as the only sane choice.

Kotlin相关问答推荐

Compose:LaunchedEffect在密钥更改后不会重新启动

Kotlin—列出具有不同T的列表之间的操作'

在KMM合成多平台中创建特定于平台的视图

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何为集成测试配置Gradle JVM测试套件?

为什么Kotlin协程程序即使有延迟也能输出?

如何创建一个空的kotlin工作?

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

Koin Android:org.koin.error.NoBeanDefFoundException

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

如何将 kotlin 集合作为 varagrs 传递?

如何在Spring Boot应用程序上启用承载身份验证?

Ktor 在 java.library.path 中没有 netty_transport_native_epoll_x86_64

什么是开放式property?为什么我不能将其设置器设为private私有?

Kotlin协程处理错误和实现

Kotlin 接口属性:只需要公共 getter 而没有公共 setter

Kotlin reflect proguard SmallSortedMap

Kotlin中保留的关键字是什么?

Kotlin for assertThat(foo, instanceOf(Bar.class))