w3resource

Scala Tuple: Swap tuple elements

Scala Tuple Exercise-5 with Solution

Write a Scala program to swap the elements of a tuple (e.g., (100, 200) should become (200, 100)).

Sample Solution:

Scala Code:

object SwapTupleElementsExample {
  def main(args: Array[String]): Unit = {
    // Create a tuple
    val nums = (100, 200)
    println("Original Tuple: "+nums)
    // Swap the elements of the tuple
    val swappedTuple = nums.swap

    // Print the swapped tuple
    println("Swapped tuple: " + swappedTuple)
  }
}

Sample Output:

Original Tuple: (100,200)
Swapped tuple: (200,100)

Explanation:

In the above exercise -

  • First, we create a tuple "nums" with elements 1 and 2.
  • To swap the tuple elements, we use the swap method, which returns a new tuple with the elements swapped.
  • We assign the resulting swapped tuple to the variable swappedTuple.
  • Finally, we print the swapped tuple using println.

Scala Code Editor :

Previous: Create a tuple from two lists.
Next: Concatenate two tuples.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.