Can someone please explain why an explicit call to apply()
is needed after map()
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l(2)
res56: Int = 3
scala> l.map(x => x*2)
res57: List[Int] = List(2, 4, 6)
scala> l.map(x => x*2)(2)
<console>:9: error: type mismatch;
found : Int(2)
required: scala.collection.generic.CanBuildFrom[List[Int],Int,?]
l.map(x => x*2)(2)
^
scala> l.map(x => x*2).apply(2)
res59: Int = 6
Thanks.
That is because map
method takes a second, implicit
argument list with a CanBuildFrom
implicit parameter:
def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
Scala compiler interprets your code as if you're trying to pass 2
where the implicit CanBuildFrom
is required.
The usage of CanBuildFrom
and ugly method signatures that come with it is a very controversial element of Scala collections library that is regularly discussed and criticized.
Another issue here is the fact that Scala allows explicit passing of implicit parameters. I would personally argue that it shouldn't be allowed and then we could avoid many issues similar to yours. But that is of course a matter of opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With