Raj
Raj

Reputation: 2398

Extracting both tuple & individual values in list using pattern matching

Here is my code

@ val lst = List((12, "aug", 2016), (13, "jun", 2016))
lst: List[(Int, String, Int)] = List((12, "aug", 2016), (13, "jun", 2016))

@ lst.foreach {
    case (day, month, year) =>
      println(s"Tpl is ($day, $month, $year)")
  }
Tpl is (12, aug, 2016)
Tpl is (13, jun, 2016)

As you can see I am able to extract the tuple into day, month & year. But the issue for me is when I want to print the tuple, I need to concatenate the values. Is there is a way to extract the complete tuple also (along with values) using pattern matching. I would need something like this(of course this do not work)

val lst = List((12, "aug", 2016), (13, "jun", 2016))
lst.foreach {
  case tpl: (day, month, year) =>
    println(s"Tpl is ($tpl)")
}

I know it is possible to do like this(shown below) ; but I am trying to avoid additional code & additional levels of indentation

@ val lst = List((12, "aug", 2016), (13, "jun", 2016))
lst: List[(Int, String, Int)] = List((12, "aug", 2016), (13, "jun", 2016))

@ lst.foreach { tpl =>
    tpl match {
      case (day, month, year) =>
        println(s"Tpl is $tpl")
    }
  }
Tpl is (12,aug,2016)
Tpl is (13,jun,2016)

Upvotes: 1

Views: 366

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

This answer is a duplicate of another answer: Scala pattern matching referencing

Replace : by @:

case tpl @ (day, month, year) =>
  println(s"Tpl is $tpl = ($day, $month, $year)")

That's called pattern binder (link to specification).

Upvotes: 3

user unknown
user unknown

Reputation: 36229

An alternative way of accessing the fields of the tuple, to Andreys code, which doesn't really show it, would be:

lst.foreach {case tpl => println (s"Tupel ${tpl} is ${tpl._1} ${tpl._2} ${tpl._3}")}
Tupel (12,aug,2016) is 12 aug 2016
Tupel (13,jun,2016) is 13 jun 2016

Upvotes: 1

Related Questions