Object destructuring with getAt in Groovy

One thing I only recently learned about Groovy is that by implementing the getAt method, you can destructure your Object via multiple assignment.

As an example, consider a class Vector2D which represents a two-dimensional vector:

Now our goal is to be able to get the x and y elements of the vector like so:

This can be achieved by adding a getAt method to our original Vector2D class

(Made a slight update so that getAt returns Double rather than double otherwise we can’t return null from the default switch case — Thanks to +Juan Vazquez for spotting this mistake)


Blog comments powered by Disqus