Scala Goodness: Tuples

Scala has a wonderful feature: Tuples. As others have already written, tuples are very simple but powerful. Especially if you come from Java, they solve some problems easily, that were ugly in Java.

What are tuples? Tuples are containers for values. In Scala you create a Tuple with:

which is syntactic sugar for

as Tuples are plain classes in the Scala library. Tuples are of type Tuple1, Tuple2, Tuple3 and so on. There currently is an upper limit of 22 in the Scala library for creating tuples, which should be enough (as is 640k of RAM). If you need more, then perhaps you really need a collection, not a tuple.

Values in tuples don’t need to be of the same type as shown here

which is one reason you should not think of them as collections (see below).

After creating a tuple there are several ways of accessing the values:

Beside accessing the values “by index”, most often it’s more readable to depack tuples into variables. Scala uses extractors for this.

Scala matches the unbound variables on the left, x and y, with the values contained in the tuple. If you need only one value, we can read one value if we want

Tuples can be used for returning multiple values from a method – something which is often missed in Java. Side note: Contrary to others I think you should consider creating a class as the return type, if it does contain semantic value and you reuse the type. We define a method which returns two values. Using the depacking from above, we assign each value to its own variable:

Tuples are not collections. As Jesse Eichar writes:

Tuples are quite handy but a potential annoyance is that at a glance they seem list-like but appearances can be deceiving. The normal collection methods are not supported by Tuples.

He gives some examples how to iterate through tuples though:

Another nice hack with Tuples: 1->2 creates a tuple in Scala.

This is used for creating maps – no need for handling this on a language level like in other languages. As before, this is defined in the Scala library not the language.

Scala glory!

43 thoughts on “Scala Goodness: Tuples”

  1. Pingback: ????? ????? ????
  2. Pingback: Portland Seo
  3. Pingback: para para dinle
  4. Pingback: cryptodyne
  5. Pingback: M88
  6. Pingback: economics tuition
  7. Pingback: porno
  8. Pingback: celtic rings
  9. Pingback: Tutoring
  10. Pingback: android apps
  11. Pingback: helpful hints
  12. Pingback: Bilskrot Göteborg
  13. Pingback: trump
  14. Pingback:
  15. Pingback: insulation
  16. Pingback: lig tv
  17. Pingback:
  18. Pingback: geisha tour
  19. Pingback: gynodel
  20. Pingback: clomed balkan

Comments are closed.