Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tuples

Exercise 1: Creating and Accessing Tuples

// Create the tuple
val book = ("The Hobbit", 1937, false)

// Access and print the elements
println(s"Title: ${book._1}")
println(s"Year: ${book._2}")
println(s"Read: ${book._3}")

Exercise 2: Tuple Destructuring

val person = ("John", "Doe", 30)

// Destructure the tuple
val (firstName, lastName, age) = person

// Print formatted string
println(s"$firstName $lastName is $age years old.")

Task: Write a function that takes two numbers as parameters, returns a tuple containing the sum and product of the two numbers.

def calculateSumAndProduct(a: Int, b: Int): (Int, Int) = {
  (a + b, a * b)
}

// Test the function
val result = calculateSumAndProduct(5, 10)
println(s"Sum: ${result._1}, Product: ${result._2}")

Task: Given a list of tuples where each tuple contains the name of a fruit and its quantity, write a code snippet that prints the name of each fruit and its quantity in a formatted string.

val fruits = List(("Apple", 10), ("Banana", 5), ("Cherry", 20))

// Iterate and print
fruits.foreach {
  case (fruit, quantity) =>
    println(s"There are $quantity $fruit(s).")
}