w3resource

Scala Tuple: Create and access the second element

Scala Tuple Exercise-1 with Solution

Write a Scala program that creates a tuple with three elements. Access the second element of the tuple.

Sample Solution:

Scala Code:

object AccessTupleElementExample {
  def main(args: Array[String]): Unit = {
    
    // Create a tuple with three elements
    val color = ("Red", 10, true)
    println("Elements of the tuple:" + color)
   
    // Access the second element of the tuple
    println("Access the second element of the tuple:")
    val secondElement = color._2

    // Print the result
    println("Second element: " + secondElement)
  }
} 

Sample Output:

Elements of the tuple:(Red,10,true)
Access the second element of the tuple:
Second element: 10

Explanation:

In the above exercise -

  • First, we create a tuple "color" with three elements: "Red", 10, true.
  • To access the second element of the tuple, we use the 2 notation, which represents the second element of the tuple. The first element is represented as 1, the second element as _2, and so on.
  • Finally, we print the second element using println.

Scala Code Editor :

Previous: Scala Tuple Exercises Home.
Next: Check if a tuple is empty or not.

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://w3resource.com/scala-exercises/tuple/scala-tuple-exercise-1.php