1

According to the Kotlin docs on destructuring declarations, the declared components should match the number of components on the right side:

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.

However, I discovered that this works even if the left hand side doesn't have the same number of components as on the right side of the assignment statement.

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

Is this legal Kotlin or is this is a bug? If it's legal, is there a reference?

1
  • 4
    "as long as the required number of component functions can be called on it" Well, Pair has component1(), so no problems here. Commented May 28, 2021 at 6:41

2 Answers 2

3

If it's legal, is there a reference?

The Kotlin Language Specification says:

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.

It says "one or more", so yes, declaring a single property by destructuring is allowed.

Also note that "required number of component functions can be called on it" doesn't mean the number of component functions has to equal to number of properties being declared. Let's put it this way: if I have 2 apples, and 1 apple is required. Do I have the "required number of apples"? Clearly the answer is yes.

If you still find it unclear, I think the spec says it better:

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.

which implies that those functions calls need to be valid. Whether or not other component functions exist is not relevant.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is what I was looking for.
2

From the document you linked to:

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.

It doesn't say it has to match the number of variables declared on the left, only that it has the required number.

In fact, this is very useful when destructuring a List:

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

The documentation for List<T>.component1():

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

Again, it doesn't restrict the list to being of size 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.