Scala Tuple (Return Multiple Values)

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 04:16:38 Viewed : 526


Scala Tuple (Return Multiple Values) 

In Scala, a tuple is a finite ordered collection of elements. Tuples are immutable, which means you cannot modify their elements once they are created. They can hold elements of different data types, making them versatile for various use cases. Tuples are zero-based, meaning you access elements using an index starting from 0.

Here is how you can create and work with tuples in Scala:

Creating Tuples:

  1. Using Parentheses:

    You can create a tuple using parentheses () and comma , to separate the elements:

    scala
    val personTuple = ("John", 30, "john@example.com")

    In this example, we create a tuple with three elements: a string, an integer, and another string.

  2. Using TupleN Classes:

    Scala provides built-in classes like Tuple2, Tuple3, up to Tuple22 for creating tuples with a specific number of elements:

    scala
    val personTuple = Tuple3("John", 30, "john@example.com")

    Here, we create a tuple with three elements using Tuple3.

Accessing Tuple Elements:

You can access tuple elements using indexing (zero-based):

scala
val name = personTuple._1 // Access the first element val age = personTuple._2 // Access the second element val email = personTuple._3 // Access the third element

Pattern Matching with Tuples:

Tuples are often used in pattern matching to extract elements:

scala
val personTuple = ("John", 30, "john@example.com") personTuple match { case (name, age, email) => println(s"Name: $name, Age: $age, Email: $email") case _ => println("Invalid tuple") }

In this example, we destructure the tuple elements using pattern matching.

Tuple Concatenation:

You can concatenate tuples using the ++ operator:

scala
val tuple1 = (1, 2) val tuple2 = (3, 4) val concatenatedTuple = tuple1 ++ tuple2

Creating a Tuple of Mixed Types:

Tuples allow mixing different types:

scala
val mixedTuple = ("John", 30, true)

Using Tuple in Collections:

Tuples can be used in collections like Lists, Maps, etc., to store pairs or triplets of values.

scala
val tupleList = List(("Alice", 25), ("Bob", 30), ("Carol", 28))

Tuples are useful when you need to group related data together and maintain their order.

Tuples are simple and handy for lightweight data structures, but for more complex data, you might consider using case classes or custom classes with named fields for better readability and maintainability.

Here are examples of working with tuples in Scala along with explanations and their respective outputs:

1. Creating Tuples:

You can create tuples in Scala using parentheses and commas to separate elements:

scala
val personTuple = ("John", 30, "john@example.com")

In this example, we create a tuple named personTuple with three elements: a string (name), an integer (age), and another string (email).

2. Accessing Tuple Elements:

You can access tuple elements using indexing (zero-based):

scala
val name = personTuple._1 // Access the first element val age = personTuple._2 // Access the second element val email = personTuple._3 // Access the third element

3. Pattern Matching with Tuples:

Tuples are often used in pattern matching to extract elements:

scala
val personTuple = ("John", 30, "john@example.com") personTuple match { case (name, age, email) => println(s"Name: $name, Age: $age, Email: $email") case _ => println("Invalid tuple") }

Output:

yaml
Name: John, Age: 30, Email: john@example.com

In this example, we destructure the personTuple using pattern matching to extract and print its elements.

4. Tuple Concatenation:

You can concatenate tuples using the ++ operator:

scala
val tuple1 = (1, 2) val tuple2 = (3, 4) val concatenatedTuple = tuple1 ++ tuple2

Output:

kotlin
concatenatedTuple: (Int, Int, Int, Int) = (1,2,3,4)

In this example, concatenatedTuple contains all the elements from tuple1 and tuple2.

5. Creating a Tuple of Mixed Types:

Tuples allow mixing different types:

scala
val mixedTuple = ("John", 30, true)

Using Tuple in Collections:

Tuples can be used in collections like Lists to store pairs or triplets of values:

scala
val tupleList = List(("Alice", 25), ("Bob", 30), ("Carol", 28))

Tuples are useful for combining related data when you want to maintain their order.

Tuples are lightweight and convenient for simple data structures, but for more complex data, consider using case classes or custom classes with named fields for better readability and maintainability.

These examples demonstrate the creation, access, and usage of tuples in Scala.

Use tuples to store multiple variables together. Return a tuple from a function.

Tuples let you put a heterogenous collection of elements in a little container. Tuples can contain between two and 22 values, and they can all be different types. For example, given a Person class like this: 

class Person(var name: String) 

You can create a tuple that contains three different types like this:

val t = (11, "Eleven", new Person("Eleven"))

You can access the tuple values by number:

t._1

t._2

t._3 

Or assign the tuple fields to variables:

val (num, string, person) = (11, "Eleven", new Person("Eleven"))  

scala.Tuple2:

A tuple of 2 elements; the canonical representation of a scala.Product2.

Parameters

_1

Element 1 of this Tuple2 

_2

Element 2 of this Tuple2

Example:

Following example illustrates about Scala tuple

Save the file as −  TupleExApp.scala  

TupleExApp.scala 

 package runnerdev

/**Scala program that uses tuples*/

object TupleExApp extends App {

  // Create and print two tuples.

  val identity1 = ("Cat"10)

  val identity2 = ("Dog"20) 

  println(identity1)

  println(identity2) 

  // Get first and second items from a tuple.

  val first = identity1._1

  val second = identity1._2 

  println(first)

  println(second)

} 

 

compile and run the above example as follows 

scala> scalac TupleExApp.scala

scala> scala TupleExApp 

Output:

(Cat,10)

(Dog,20)

Cat

10 

Example 2:

Following example illustrates about Scala tuple program that returns from function

Save the file as −  TupleExApp2.scala 

TupleExApp2.scala 

 package runnerdev

/**Scala program that uses tuples*/

object TupleExApp2 extends App { 

  // This def returns a two-item tuple.

  // It uppercases the argument String.

  def upperName(nameString): (StringString) = (name.toUpperCase(), name) 

  // Call upperName function with String.

  val name = "scala Porgram"

  val upperRes = upperName(name)

  println(upperRes) 

  //Scala program that unpacks tuple

  // Return a tuple.

  def multiplyNum(x: Int): (Int, Int) = (x * 3x * 4) 

  // Unpack the tuple returned by the function.

  val (number1number2) = multiplyNum(5)

  println(number1)

  println(number2) 

 

compile and run the above example as follows 

scala> scalac TupleExApp2.scala

scala> scala TupleExApp2 

Output:

(SCALA PORGRAM,scala Porgram)

15

20 

Example 3:

Following example illustrates about Scala program that uses tuple with match  case

Save the file as −  TupleExApp3.scala 

TupleExApp3.scala 

 package runnerdev

/** Scala program that uses tuple with match  */

object TupleExApp3 extends App { 

  def matchMethod(animal: (String, Int)) = {

    animal match {

      case ("dog"size) =>

        println("dog weighs"size)

      case (animalsize) =>

        println("Other animal"animalsize)

    }

  } 

  // Call test method with tuple argument.

  val animal1 = ("dog"60)

  matchMethod(animal1) 

  val animal2 = ("cat"30)

  matchMethod(animal2)

} 

compile and run the above example as follows 

scala> scalac ForLoopAndYield.scala

scala> scala ForLoopAndYield 

Output:

(dog weighs,60)

(Other animal,cat,30) 

Example 3:

Following example illustrates about Scala program that uses list of tuples

Save the file as −  TupleExApp5.scala

  TupleExApp5.scala 

 package runnerdev

/** Scala program that uses list of tuples  */

object TupleExApp5 extends App { 

  // Create list of tuples.

  val employee = List(("Bonam"101"Bangalore"), ("Prasad"102"Singapore"),("Ram"103"Singapore")) 

  // Loop over tuples.

  for (value <- employee) {

    println(value._1 + " from " + value._3)

    println(" employeeId " + value._2)

  }

} 

compile and run the above example as follows 

scala> scalac TupleExApp5.scala

scala> scala TupleExApp5 

Output :

Bonam from Bangalore

  employeeId 101

Prasad from Singapore

  employeeId 102

Ram from Singapore

                employeeId 103   

Search
Related Articles

Leave a Comment: