I am trying to understand mapConserve, which is said to be “Like xs map f, but returns xs unchanged if function f maps all elements to themselves,” from List. Yet, it is giving out error.
def map [B] (f: (A) ⇒ B): List[B]
def mapConserve (f: (A) ⇒ A): List[A]
def mapConserve [B >: A <: AnyRef] (f: (A) ⇒ B): List[B]
scala> list map (x=>x)
res105: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> list mapConserve (x=>x)
<console>:12: error: inferred type arguments [Int] do not conform to method mapConserve's type parameter bounds [B >: Int <: AnyRef]
list mapConserve (x=>x)
^
The mapConserve code should satisfy the (A) => A function. If not, it still should satisfy the (A) => B function, since type A can be subtype and supertype of itself. Please enlighten me the purpose of mapConserve and the error.
Actually,
mapConserveis defined asso
Ashould be a subtype ofAnyRef.Intis a subtype ofAnyVal, that brings an error.Update:
The only difference between
mapandmapConserve, as it is described in the scaladoc:And
xs mapConserve identityis about five times faster in my simple benchmark.