只有一个声明参数的 Kotlin 解构声明

Kotlin destructuring declaration with only one declared parameter

根据Kotlin docs on destructuring declarations,声明的组件应该匹配右侧的组件数:

Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it.

但是,我发现即使左侧的组件数量与赋值语句右侧的组件数量不同,这仍然有效。

fun main() {   
    val (firstOnly) = Pair("key", "value")
    println("firstOnly=${firstOnly}")
}

这是合法的 Kotlin 还是一个错误?如果合法的话,有参考吗?

If it's legal, is there a reference?

The Kotlin Language Specification 说:

A special case of definition by convention is the destructuring declaration of properties [...]

This convention allows to introduce a number (one or more) of properties in the place of one by immediately destructuring the property during construction.

它说“一个或多个”,所以是的,允许通过解构声明单个 属性。

另请注意,“可以在其上调用所需数量的组件函数”并不意味着组件函数的数量必须 等于 声明的属性数量。这么说吧:如果我有2个苹果,1个苹果是required。我有“所需数量的苹果”吗?显然答案是肯定的。

如果你还是觉得不清楚,我觉得规范说得更好:

For each identifier the corresponding operator function componentK with K being equal to the position of the placeholder in the declaration (starting from 1) is called without arguments.

这意味着那些函数调用需要有效。其他组件功能是否存在无关

来自您链接到的文档:

Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it.

并没有说它必须匹配左边声明的变量数量,只是说它有要求的数量。

事实上,这在解构 List 时非常有用:

val (first, second) = listOf(1, 2, 3, 4, 5)

List<T>.component1() 的文档:

Throws an IndexOutOfBoundsException if the size of this list is less than 1.

同样,它不会将列表的大小限制为 1。