Tuples and Multiple Assignments

In Java, while methods can take multiple arguments, they can only return one result. Returning more than a single value needs clumsy workarounds in Java. For example, to return a person’s first name, last name, and email address we’d have to employ a Person class and return an array of Strings or an ArrayList. Scala’s Tuple, combined with multiple assignments, makes returning multiple values a simple task.

A tuple is an immutable object sequence created as comma-separated values. For example, the following represents a tuple with three objects: ("Venkat", "Subramaniam", "[email protected]").

You can assign the elements of a tuple into multiple vals or vars in parallel, as we see here:

FromJavaToScala/MultipleAssignment.scala
 
def​ getPersonInfo(primaryKey : ​Int​) = {
 
// Assume primaryKey is used to fetch a person's info...
 
// Here response is hard-coded
 
(​"Venkat"​, ​"Subramaniam"​, ​"[email protected]"​)
 
}
 
 
val​ (firstName, lastName, emailAddress) = getPersonInfo(1)
 
 
println(s​"First Name: $firstName"​)
 
println(s​"Last Name: $lastName"​)
 
println(s​"Email Address: $emailAddress"​)

Here’s the output from executing this code:

 
First Name: Venkat
 
Last Name: Subramaniam
 
Email Address: [email protected]

If you assign the result of the method to fewer variables or to more variables Scala will keep an eye out and report an error. This error reporting is done at compile time for source code or during the compilation phase if run as a script. For example, in the following we’re assigning the result of the method call to fewer variables than in the tuple:

FromJavaToScala/MultipleAssignment2.scala
 
def​ getPersonInfo(primaryKey : ​Int​) = {
 
(​"Venkat"​, ​"Subramaniam"​, ​"[email protected]"​)
 
}
 
 
val​ (firstName, lastName) = getPersonInfo(1)

Scala will report this error:

 
MultipleAssignment2.scala:5: error: constructor cannot be instantiated to
 
expected type;
 
found : (T1, T2)
 
required: (String, String, String)
 
val (firstName, lastName) = getPersonInfo(1)
 
^
 
one error found

Instead of assigning the values, you can also access individual elements of a tuple. For example, if we execute val info = getPersonInfo(1), then we can access the first element using the syntax info._1, the second element using info._2, and so on.

The underscore paired with a number, like _1, represents the index or position of the element we’d like to access in a tuple. Unlike collections, tuples are accessed using a 1-based index. Also, unlike collections, if you specify an index out of range, you get a compilation error instead of runtime error—pretty nifty, eh?

Some programmers complain about the underscore being used to index tuples. They say that the dot-underscore is unwieldy and hard to read. If you don’t like underscores there’s an easy way to deal with it—get over it (just kidding).

Tuples are useful not only for multiple assignments. They’re useful to pass a list of data values as messages between actors in concurrent programming, and their immutable nature comes in handy here. Their concise syntax helps keep the code on the message sender side very concise. On the receiving side, you can use pattern matching to concisely receive and process the message, as you’ll see in Matching Tuples and Lists.

Returning multiple values from methods and functions is quite convenient, Scala also has some things for passing arguments.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.193.244