Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pair<L, R> in Groovy

Tags:

groovy

Does Groovy support Pairs (e.g. from Java or C++)? If not, what would be a good way to get around this?

like image 910
450F Avatar asked Sep 09 '16 21:09

450F


People also ask

What is the pattern operator in Groovy?

2. Pattern Operator The Groovy language introduces the so-called pattern operator ~. This operator can be considered a syntactic sugar shortcut to Java's java.util.regex.Pattern.compile (string) method. This is also pretty convenient, but we'll see that this operator is merely the baseline for some other, even more useful operators. 3.

What is the match operator in Groovy?

3. Match Operator Most of the time, and especially when writing tests, we're not really interested in creating Pattern objects, but instead, want to check if a String matches a certain regular expression (or Pattern ). Groovy, therefore, also contains the match operator ==~.

How to join strings in Groovy?

Quite simply, we can use the + operator to join String s: Similarly, Groovy also supports the left shift << operator: 3. String Interpolation As a next step, we'll try to improve the readability of the code using a Groovy expression within a string literal:

How do triple-double-quoted strings behave in Groovy?

Triple-double-quoted strings behave like double-quoted strings, with the addition that they are multiline, like the triple-single-quoted strings. def name = 'Groovy' def template = """ Dear Mr $ {name}, You're the winner of the lottery! Yours sincerly, Dave """ assert template.toString().contains('Groovy')


1 Answers

Groovy has a Tuple2 class as Gergely's answer states.

However, there's an alternative to returning a Pair or tuple that may be easier; Groovy supports a feature called multiple assignment, where you can assign the members of an array or list to different variables:

groovy:000> (a, b) = [1, 2]
===> [1, 2]
groovy:000> a
===> 1
groovy:000> b
===> 2

The variables don't have to have the same type.

So you can return a list with two entries from a method call, and let the caller assign them to different variables, without having to involve any kind of specialized container like a Pair or Tuple2 where you'd have to unpack the values from it.

If you want a well-defined contract with explicit names, then go with your own class. Alternatively use a Map so you can at least use the keys to assign names to the different things being returned.

Using a Tuple2 or Pair is as order-sensitive as using multiple assignment, is zero improvement with respect to naming, and adds extra boilerplate code to pack and unpack.

like image 59
Nathan Hughes Avatar answered Oct 24 '22 20:10

Nathan Hughes