Skip to content

Commit 62783e8

Browse files
authored
Add mutable Map.updateWith (#508)
1 parent 2b60efa commit 62783e8

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,10 @@ private[compat] trait PackageShared {
271271
self: scala.collection.Map[K, V]): MapExtensionMethods[K, V] =
272272
new MapExtensionMethods[K, V](self)
273273

274+
implicit def toMutableMapExtensionMethods[K, V](
275+
self: scala.collection.mutable.Map[K, V]): MutableMapExtensionMethods[K, V] =
276+
new MutableMapExtensionMethods[K, V](self)
277+
274278
implicit def toMapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
275279
self: IterableView[(K, V), C]): MapViewExtensionMethods[K, V, C] =
276280
new MapViewExtensionMethods[K, V, C](self)
@@ -523,6 +527,19 @@ class MapExtensionMethods[K, V](private val self: scala.collection.Map[K, V]) ex
523527

524528
}
525529

530+
class MutableMapExtensionMethods[K, V](private val self: scala.collection.mutable.Map[K, V])
531+
extends AnyVal {
532+
533+
def updateWith(key: K)(remappingFunction: (Option[V]) => Option[V]): Option[V] = {
534+
val updatedEntry = remappingFunction(self.get(key))
535+
updatedEntry match {
536+
case Some(v) => self.update(key, v)
537+
case None => self.remove(key)
538+
}
539+
updatedEntry
540+
}
541+
}
542+
526543
class MapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
527544
private val self: IterableView[(K, V), C])
528545
extends AnyVal {
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
import scala.collection.{mutable => m}
20+
21+
class MutableMapTest {
22+
23+
@Test
24+
def updateWith: Unit = {
25+
val map = m.Map("a" -> 1, "c" -> 3)
26+
map.updateWith("b") {
27+
case None => Some(2)
28+
case Some(x) => Some(-1)
29+
}
30+
map.updateWith("c") {
31+
case None => Some(-1)
32+
case Some(_) => None
33+
}
34+
assertEquals(map.get("b"), Some(2))
35+
assertFalse(map.contains("c"))
36+
}
37+
38+
}

0 commit comments

Comments
 (0)