Actually, mapConserve is defined as
def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] def mapConserve[B >: A <: AnyRef](f: A => B): List[B]
therefore A must be a subtype of AnyRef . Int is a subtype of AnyVal that results in an error.
scala> val l = List("foo", "bar", "baz") l: List[java.lang.String] = List(foo, bar, baz) scala> l.mapConserve(_.toUpperCase) res4: List[java.lang.String] = List(FOO, BAR, BAZ) scala> l.mapConserve(identity) res5: List[java.lang.String] = List(foo, bar, baz)
Update:
The only difference between map and mapConserve , as described in scaladoc :
Creates a new list, applying the function to all elements of this list. Like xs map f, but returns xs unchanged if the function f maps all elements to itself (as defined by eq).
scala> val xs = List.fill(1000000)("foo") xs: List[java.lang.String] = List(foo, foo,...) scala> xs.map(identity) eq xs res48: Boolean = false scala> xs.mapConserve(identity) eq xs res49: Boolean = true
And xs mapConserve identity about five times faster in my simple test.
source share