Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of destructuring declarations in Kotlin?

Tags:

kotlin

I have come across the concept called destructuring declarations - when you can return multiple values from a function at once. It seems very convenient, but at the same time it looks like a tricky workaround. Each time when I think about that feature in Java, I understand that it's a hole in my architecture - there should probably be a class then, not just a couple of variables.

What do you think?

like image 222
G. Kh. Avatar asked Mar 08 '23 06:03

G. Kh.


1 Answers

The concept allows having classes that clearly identify a few of their primary properties, the components.

Then you can access these components by using a destructuring declaration, without syntactic noise of accessing the properties.

Compare:

 val point = clickEvent.getPointOnScreen()
 val x = point.xCoordinate
 val y = point.yCoordinate
 // Use `x` and `y` in some calculations

and, assuming that the type has component1 and component2, just:

 val (x, y) = clickEvent.getPointOnScreen()

Basically, it is not necessary to use this sort of syntactic sugar, and the concept itself does not harm any of the abstractions, it only provides a convenient way to access properties of a class instance in some cases when you don't need the instance itself.

Another example is working with map entries, e.g:

for ((key, value) in myMap) { /* ... */ }

There's still a Map.Entry<K, V> behind the (key, value) destructuring, and you can replace it by for (entry in myMap) ..., but usually it's the two properties that you need. This is where destructuring saves you from a little syntactic noise.

like image 77
hotkey Avatar answered Mar 20 '23 09:03

hotkey