w3resource

Scala Tuple: Concatenate two tuples

Scala Tuple Exercise-6 with Solution

Write a Scala program to concatenate two tuples: (200, "Scala") and (300, "Exercises") should become ("Scala Exercises", 500).

Sample Solution:

Scala Code:

object ConcatenateTuplesExample {
  def main(args: Array[String]): Unit = {
    // Create two tuples
    val tuple1 = (200, "Scala")
    val tuple2 = (300, "Exercises")
    println("Tuple1: "+tuple1)
    println("Tuple2: "+tuple2)
    // Concatenate the tuples
    val concatenatedTuple = (tuple1._1 + tuple2._1, tuple1._2 + " " + tuple2._2)

    // Print the concatenated tuple
    println("Concatenated tuple: " + concatenatedTuple)
  }
}

Sample Output:

Tuple1: (200,Scala)
Tuple2: (300,Exercises)
Concatenated tuple: (500,Scala Exercises)

Explanation:

In the above exercise -

  • We have two tuples: tuple1 with elements (200, "Scala") and tuple2 with elements (300, "Exercises").
  • To concatenate the tuples, we create a new tuple concatenatedTuple where the first element is the concatenation of the second elements of tuple1 and tuple2. The second element is the sum of both tuples.
  • We access the elements of the tuples using the 1 and 2 notation, where 1 represents the first element and 2 represents the second element.
  • Finally, we print the concatenated tuple using println.

Scala Code Editor :

Previous: Swap tuple elements.
Next: Check if a specific element exists in a tuple.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/tuple/scala-tuple-exercise-6.php