Dear friends : what’s the difference between using and not using case in map methods:
(List(10, 20) zip List(3, 4, 5)).
map { case (x, y) => x * y } // not compile if don’t use case
(List(10, 20) zip List(3, 4, 5)).
map { p => p._1 * p._2 } // here what is the difference of map param with above example
(List(10, 20) lazyZip List(3, 4, 5)).
map { (x, y) => x * y } // works
(List(10, 20) lazyZip List(3, 4, 5)).
map { case (x, y) => x * y } //works
So the thing is zip
returns a List[(A, B)]
so still a List and map
expects a Function of just one argument (just that in this case that one argument is a tuple); thus:
(List(10, 20) zip List(3, 4, 5)).map { (x, y) => x * y }
// Does not work because that is a function of two arguments and map expect a function of one argument.
(List(10, 20) zip List(3, 4, 5)).map { case (x, y) => x * y }
// Works because due pattern matching we deconstruct the tuple.
(List(10, 20) zip List(3, 4, 5)).map(tuple => tuple match { case (x, y) => x * y })
// This is what the previous snippet desugars to.
However lazyZip
returns a LazyZip2[Int, Int, List]
so not really a List but some other different class, and the map
method on that class expects a Function of two arguments; thus:
(List(10, 20) lazyZip List(3, 4, 5)).map { (x, y) => x * y }
// Works because that map expects a function of two arguments.
(List(10, 20) lazyZip List(3, 4, 5)).map { (x, y) => x * y }
// Works because of sugar syntax.
(List(10, 20) lazyZip List(3, 4, 5)).map((x1, y1) => (x1, y1) match { case (x, y) => x * y })
// This is what the previous snippet desugars to.
2 Likes