w3resource

Scala Tuple: Checking equality of two tuples

Scala Tuple Exercise-10 with Solution

Write a Scala program to check if two tuples are equal.

Sample Solution:

Scala Code:

object CheckTupleEqualityExample {
  def main(args: Array[String]): Unit = {
    // Create two tuples
    val tuple1 = (1, "Kotlin", true)
    val tuple2 = (1, "Kotlin", true)
    val tuple3 = (2, "Java", false)
    println("Tuple1: "+tuple1)
    println("Tuple2: "+tuple2)
    println("Tuple3: "+tuple3)
    // Check if the tuples are equal
    val areEqual1 = tuple1 == tuple2
    val areEqual2 = tuple1 == tuple3

    // Print the results
    println(s"Are tuple1 and tuple2 equal? $areEqual1")
    println(s"Are tuple1 and tuple3 equal? $areEqual2")
  }
}

Sample Output:

Tuple1: (1,Kotlin,true)
Tuple2: (1,Kotlin,true)
Tuple3: (2,Java,false)
Are tuple1 and tuple2 equal? true
Are tuple1 and tuple3 equal? false

Explanation:

In the above exercise -

  • First we create three tuples: tuple1 with elements (1, "Kotlin", true), tuple2 with the same elements as tuple1, and tuple3 with different elements (2, "Java", false).
  • To check if two tuples are equal, we use the == operator. It compares the corresponding elements of the tuples and returns true if all elements are equal.
  • The resulting Boolean values are assigned to the variables areEqual1 and areEqual2.
  • Finally, we print the results using println.

Scala Code Editor :

Previous: Find distinct elements in a tuple.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.