Alexandr
Alexandr

Reputation: 349

get tuple as arguments from zipWithIndex in scala

I can pass and use values from tuple like this in for

for ((v,i) <- in.zipWithIndex) {
        println(s"$i is $v")
      }

But in foreach it's used only like

in.zipWithIndex.foreach {
    case(v, i) => println(s"$i is $v")
}

How can I make something like function

val f: (Int,Int) => Unit = (v,i) => {println(s"$i is $v")}

and then pass it into .foreach(). AND (it's important just for me) without using pattern matching case.

P.S. .tupled works only for methods (def). not for function defined as val

Upvotes: 0

Views: 278

Answers (1)

Terry Dactyl
Terry Dactyl

Reputation: 1868

The argument to your function needs to be a Tuple.

scala> val l = List(1,2,3).zipWithIndex                      
l: List[(Int, Int)] = List((1,0), (2,1), (3,2))              

scala> val f = (t: (Int, Int)) => println(s"${t._1} ${t._2}")
f: ((Int, Int)) => Unit = <function1>                        

scala> l.foreach(f)                                          
1 0                                                          
2 1                                                          
3 2   

Personally I hate the ._1, ._n syntax and prefer to pattern match on tuples.

BTW your for comprehension example is also using pattern matching...

Upvotes: 1

Related Questions