Reputation: 9705
I'm looking for an elegant way of accessing two items in a Seq
at the same time. I've checked earlier in my code that the Seq
will have exactly two items. Now I would like to be able to give them names, so they have meaning.
records
.sliding(2) // makes sure we get `Seq` with two items
.map(recs => {
// Something like this...
val (former, latter) = recs
})
Is there an elegant and/or idiomatic way to achieve this in Scala?
Upvotes: 1
Views: 1083
Reputation: 27356
I'm not sure if it is any more elegant, but you can also unpick the sequence like this:
val former +: latter +: _ = recs
Upvotes: 3
Reputation: 28322
The result of sliding
is a List
. Using a pattern match, you can give name to these elements like this:
map{ case List(former, latter) =>
...
}
Note that since it's a pattern match, you need to use {}
instead of ()
.
Upvotes: 1
Reputation: 36229
For a records of known types (for example, Int):
records.sliding (2).map (_ match {
case List (former:Int, latter:Int) => former + latter })
Note, that this will unify element (0, 1), then (1, 2), (2, 3) ... and so on. To combine pairwise, use sliding (2, 2):
val pairs = records.sliding (2, 2).map (_ match {
case List (former: Int, latter: Int) => former + latter
case List (one: Int) => one
}).toList
Note, that you now need an extra case for just one element, if the records size is odd.
Upvotes: 0
Reputation: 6801
You can use pattern matching to decompose the structure of your list:
val records = List("first", "second")
records match {
case first +: second +: Nil => println(s"1: $first, 2: $second")
case _ => // Won't happen (you can omit this)
}
will output
1: first, 2: second
Upvotes: 1
Reputation: 95948
You can access the elements by their index:
map { recs => {
val (former, latter) = recs(0), recs(1)
}}
Upvotes: 1