w3resource

Scala Tuple: Check if a tuple is empty or not

Scala Tuple Exercise-2 with Solution

Write a Scala program that checks if a tuple is empty or not.

Sample Solution:

Scala Code:

object CheckTupleEmptyExample {
  def main(args: Array[String]): Unit = {
    // Create an empty tuple
    val tuple1 = ()

    // Create a non-empty tuple
    val tuple2 = ("Red", 10, true)

   // Check if the tuples are empty
    val isEmpty1 = tuple1 == ()
    val isEmpty2 = tuple2 == ()

    // Print the result
    println("Is tuple1 is empty? " + isEmpty1)
    println("Is tuple2  empty? " + isEmpty2)
  }
}

Sample Output:

Is tuple1 is empty? true
Is tuple2  empty? false

Scala Code Editor :

Previous: Create and access the second element.
Next: Create a tuple with squares of numbers.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.