Proposals: Destructuring assignment
Sayakie opened this issue ยท 0 comments
Unpacks values from arrays into distinct variables. This capability is similar to features present in languages such as JavaScript, Perl and Python.
Syntax
fruits = arrayOf("apple", "banana", "blueberry")
[apple, banana, blueberry] = fruits
#LOG apple // Prints "apple"
#LOG banana // Prints "banana"
#LOG blueberry // Prints "blueberry"
balls = arrayOf("PokeBall", "DiveBall", "GreatBall", "MasterBall")
[pokeball, , , masterball] = balls
#LOG pokeball // Prints "PokeBall"
#LOG masterball // Prints "MasterBall"
[pokeball, ...others] = balls
#LOG others // Prints "[DiveBall, GreatBall, MasterBall]"
#LOG others.length // Prints "3"
#LOG others IS Array // Prints "true"
#LOG others.getClass() // Prints "java.lang.String[]"
Default value
Each destructured property can have a default value. The default value is used when the property is not present, or has value null
.
[a, b = 2] = arrayOf(1)
#LOG b // Prints "2"
The default value MUST be type of the right-hand side. So the following code will be thrown an exception:
[a, b = "2"] = arrayOf(1)
// Raise ParserException caused by ArrayStoreException
Rest property
As you can see in syntax section, you can end a destructuring pattern with a rest property(...rest
). This pattern will store all remaining properties of the array into a new array.
[pokeball, ...others] = balls
#LOG others // Prints "[DiveBall, GreatBall, MasterBall]"
#LOG others.length // Prints "3"
#LOG others IS Array // Prints "true"
#LOG others.getClass() // Prints "java.lang.String[]"
The rest property must be last in the pattern, and must not have atrailing command.
[pokeball, ...others, ] = balls
// Raise ParserException
// Message probably like: Rest element may not have a trailing comma.