Scala Tuple: Merge two tuples into a single tuple
Scala Tuple Exercise-8 with Solution
Write a Scala program that merges two tuples into a single tuple.
Sample Solution:
Scala Code:
object MergeTuplesExample {
def main(args: Array[String]): Unit = {
// Create two tuples
val tuple1 = (10, "Scala")
val tuple2 = (15.5, true)
println("Tuple1 elements: "+tuple1)
println("Tuple2 elements: "+tuple2)
// Merge the tuples
val mergedTuple = (tuple1._1, tuple1._2, tuple2._1, tuple2._2)
// Print the merged tuple
println("Merged tuple: " + mergedTuple)
}
}
Sample Output:
Tuple1 elements: (10,Scala) Tuple2 elements: (15.5,true) Merged tuple: (10,Scala,15.5,true)
Explanation:
In the above exercise -
- We have two tuples: tuple1 with elements (10, "Scala") and tuple2 with elements (15.5, true).
- To merge the tuples, we create a new tuple mergedTuple by specifying all the elements from tuple1 and tuple2 in the desired order.
- The elements of the tuples are represented by the 1 and 2 notations, where 1 represents the first element and 2 represents the second.
- Finally, we print the merged tuple using println.
Scala Code Editor :
Previous: Check if a specific element exists in a tuple.
Next: Find distinct elements in a tuple.
What is the difficulty level of this exercise?
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-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics