Rocky
Rocky

Reputation: 51

how to find the tuple value using scala?

val x=(1,(2,(3,(4,5))))

how the get the 4 from above using Scala?

can someone please to find the value using the Scala code

Upvotes: 3

Views: 181

Answers (2)

Guru Stron
Guru Stron

Reputation: 143531

You can access individual elements of tuple by position with individual elements being named _1, _2 etc. :

val four = x._2._2._2._1

Or using pattern matching:

val (_,(_,(_,(four,_)))) = x

Upvotes: 5

zagyi
zagyi

Reputation: 17528

You can use pattern matching to decompose the expression:

scala> val (a,(b,(c,(d,e)))) = (1,(2,(3,(4,5))))
a: Int = 1
b: Int = 2
c: Int = 3
d: Int = 4
e: Int = 5

In case you are not interested in other values than 4:

scala> val (_, (_, (_, (x, _)))) = (1,(2,(3,(4,5))))
x: Int = 4

Upvotes: 6

Related Questions