Scala Tuple: Create and access the second element
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics