gpt4 book ai didi

Kotlin - 构造函数默认值和构造函数重载

转载 作者:行者123 更新时间:2023-12-01 12:05:28 28 4
gpt4 key购买 nike

考虑以下代码:

class Foo(val bar: String, val baz: Boolean = true) {
constructor(bar: String) : this(bar, false)
}

如果不添加辅助构造函数,我可以调用 Foo("")因为第二个参数有一个默认值。这将导致 baz正在 true .

添加辅助构造函数后,我仍然可以调用 Foo("") ,除了现在 bazfalse .

为什么 Kotlin 不认为这是重复的构造函数签名,因为它们都可以用相同的参数调用?

最佳答案

如果你看一下字节码,实际上生成了三个构造函数,正如 Roland 已经指出的那样。

public Foo(@NotNull String bar, boolean baz) { ... }
public Foo(String var1, boolean var2, int var3, DefaultConstructorMarker var4) { ... }
public Foo(@NotNull String bar) { ... }

因此,没有重复的构造函数签名。现在有人可能会问 Kotlin 如何选择仅从调用站点判断的重载。

总体原理是将从重载候选中选择最具体的函数/构造函数。

这是什么 Kotlin language specification说到:

  • For each candidate, we count the number of default parameters not specified in the call (i.e., the number of parameters for which we use the default value);

  • The candidate with the least number of non-specified default parameters is a more specific candidate;



我知道您希望这只是一个例子,但如果在现实世界中发生这样的事情,应该避免它,例如 Kotlin Language Documentation (第 76 页)指出:

If you have an object with multiple overloaded constructors that don't call different superclass constructors and can't be reduced to a single constructor with default argument values, prefer to replace the overloaded constructors with factory functions.


class Foo2(val bar: String, val baz: Boolean = true) {
companion object {
fun factoryCreate(s: String) = Foo2(s, false)
}
}

在这种情况下,总是会立即清楚(无需考虑重载解析规则)是什么 baz将在创建之后。

关于Kotlin - 构造函数默认值和构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57873560/

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