Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
C HAPTER 3 ยท Next Steps in Scala Step 9. Use tuples Another useful container object is the tuple. Like lists, tuples are immutable, but unlike lists, tuples can contain different types of elements. Whereas a list might be a List[Int] or a List[String] , a tuple could contain both an integer and a string at the same time. Tuples are very useful, for example, if you need to return multiple objects from a method. Whereas in Java you would often create a JavaBean-like class to hold the multiple return values, in Scala you can simply return a tuple. And it is simple: to instantiate a new tuple that holds some objects, just place the objects in parentheses, separated by commas. Once you have a tuple instantiated, you can access its elements individually with a dot, underscore, and the one-based index of the element. An example is shown in Listing 3.4: val pair = (99, "Luftballons") println(pair._1) println(pair._2) Listing 3.4 ยท Creating and using a tuple.