Scala list index

Can someone explain why an explicit call is apply()needed aftermap()

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.

+4
source share
1 answer

This is because the method mapaccepts a second, implicitlist of arguments with an implicit parameter CanBuildFrom:

def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That

The Scala compiler interprets your code as if you were trying to pass 2where implicit is required CanBuildFrom.

Using the signatures CanBuildFromand the ugly methods that come with it is a very controversial element of the Scala collection library, which is regularly discussed and criticized.

, Scala . , , , . , , .

+7

All Articles