Skip to content

Commit 016b68c

Browse files
authored
Merge pull request scala#220 from szeiger/issue/203
Add mapValues for IterableViews of Maps
2 parents 9f8a1c1 + 71dda91 commit 016b68c

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ package scala.collection.compat
1414

1515
import scala.collection.generic._
1616
import scala.reflect.ClassTag
17-
import scala.collection.{MapLike, GenTraversable, BitSet}
17+
import scala.collection.{MapLike, GenTraversable, BitSet, IterableView}
1818
import scala.collection.{immutable => i, mutable => m}
1919
import scala.{collection => c}
2020

@@ -155,6 +155,9 @@ private[compat] trait PackageShared {
155155
// in scala-library so we can't add to it
156156
type IterableOnce[+X] = c.TraversableOnce[X]
157157
val IterableOnce = c.TraversableOnce
158+
159+
implicit def toMapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](self: IterableView[(K, V), C]): MapViewExtensionMethods[K, V, C] =
160+
new MapViewExtensionMethods[K, V, C](self)
158161
}
159162

160163
class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal {
@@ -231,3 +234,8 @@ class TraversableOnceExtensionMethods[A](private val self: c.TraversableOnce[A])
231234
class TraversableExtensionMethods[A](private val self: c.Traversable[A]) extends AnyVal {
232235
def iterableFactory: GenericCompanion[Traversable] = self.companion
233236
}
237+
238+
class MapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](private val self: IterableView[(K, V), C]) extends AnyVal {
239+
def mapValues[W, That](f: V => W)(implicit bf: CanBuildFrom[IterableView[(K, V), C], (K, W), That]): That =
240+
self.map[(K, W), That] { case (k, v) => (k, f(v)) }
241+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Scala (https://www.scala-lang.org)
3+
*
4+
* Copyright EPFL and Lightbend, Inc.
5+
*
6+
* Licensed under Apache License 2.0
7+
* (http://www.apache.org/licenses/LICENSE-2.0).
8+
*
9+
* See the NOTICE file distributed with this work for
10+
* additional information regarding copyright ownership.
11+
*/
12+
13+
package test.scala.collection
14+
15+
import org.junit.Test
16+
import org.junit.Assert._
17+
18+
import scala.collection.compat._
19+
20+
class ViewTest {
21+
22+
@Test
23+
def mapValues: Unit = {
24+
val m = Map("a" -> 1, "b" -> 2, "c" -> 3)
25+
val oldStyle = m.mapValues(x => x*x)
26+
val newStyle = m.view.mapValues(x => x*x)
27+
assertEquals(oldStyle.toMap, newStyle.toMap)
28+
}
29+
30+
}

0 commit comments

Comments
 (0)