Scala: What does zipped do and why can it be matched as a pair?

In an earlier question about zipWith, @Martin Odersky suggested that instead of something like

 foo zipWith(_ + _) bar

(where fooand barare the Seq's), which should be better (and actually works in Scala).

(foo, bar).zipped map (_ + _)

My question is, how mapdoes it know that its argument (which looks like a couple) should be split into two of its elements?

The worksheet actually does the following.

val list1 = List(1, 2, 3, 4)                    //> list1  : List[Int] = List(1, 2, 3, 4)
val list2 = List(5, 6, 7, 8)                    //> list2  : List[Int] = List(5, 6, 7, 8)
val zippedResult = (list1, list2).zipped        //> list3  : scala.runtime.Tuple2Zipped[Int,List[Int],Int,List[Int]] = scala.run
                                              //| time.Tuple2Zipped@f4bf78da
zippedResult.mkString(", ")                     //> res4: String = (1,5), (2,6), (3,7), (4,8)
zippedResult map (_ + _)                        //> res5: List[Int] = List(6, 8, 10, 12)

I see that it zippedResultactually has 4 type parameters and is not just a list of pairs.

val list3 = List((1, 5), (2, 6), (3, 7), (4, 8))
                                              //> list3a  : List[(Int, Int)] = List((1,5), (2,6), (3,7), (4,8))
list3 == zippedResult                           //> res6: Boolean = false

And I can not write

list3 map(_ +_ )

So what is a type Tuple2Zippedthat can provide two function parameters map? And the zippedonly way to create instances of it?

+3
1

runtime.Tuple2Zipped. :

val zipped = new Tuple2Zipped(Seq(1, 2), Seq(3, 4))

map.

map ():

def map[B](f: (El1, El2) => B): Seq[B]

Tuple2Zipped - scala, map map scala.

+5

All Articles