Sometimes we run into a case when a function logically needs to return multiple values. Some examples are returning coordinates of a point, returning some statistical data, returning error information like the error code and the message, etc.
Important
Records require a language version of at least 3.0.
Previously, when we wanted to return more than one object from a function, we had to create an additional class or add a package like Tuple.
The following code snippet shows that to return the name
and age
from a function, we had to create a class called User
:
Now let’s see the difference using records.
We can see that using records, it is not necessary to create a User class.
Records Syntax
Records expressions are comma-delimited lists of named or positional fields, enclosed in parentheses:
Records and Pattern Destructuring
We can even use destructuring, which is a pattern matching technique, to extract and assign values from a data structure into individual variables concisely and efficiently. The code would look like this:
References