Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,10 @@ private[compat] trait PackageShared {
self: scala.collection.Map[K, V]): MapExtensionMethods[K, V] =
new MapExtensionMethods[K, V](self)

implicit def toMutableMapExtensionMethods[K, V](
self: scala.collection.mutable.Map[K, V]): MutableMapExtensionMethods[K, V] =
new MutableMapExtensionMethods[K, V](self)

implicit def toMapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
self: IterableView[(K, V), C]): MapViewExtensionMethods[K, V, C] =
new MapViewExtensionMethods[K, V, C](self)
Expand Down Expand Up @@ -523,6 +527,19 @@ class MapExtensionMethods[K, V](private val self: scala.collection.Map[K, V]) ex

}

class MutableMapExtensionMethods[K, V](private val self: scala.collection.mutable.Map[K, V])
extends AnyVal {

def updateWith(key: K)(remappingFunction: (Option[V]) => Option[V]): Option[V] = {
val updatedEntry = remappingFunction(self.get(key))
updatedEntry match {
case Some(v) => self.update(key, v)
case None => self.remove(key)
}
updatedEntry
}
}

class MapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
private val self: IterableView[(K, V), C])
extends AnyVal {
Expand Down
38 changes: 38 additions & 0 deletions compat/src/test/scala/test/scala/collection/MutableMapTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package test.scala.collection

import org.junit.Test
import org.junit.Assert._

import scala.collection.compat._
import scala.collection.{mutable => m}

class MutableMapTest {

@Test
def updateWith: Unit = {
val map = m.Map("a" -> 1, "c" -> 3)
map.updateWith("b") {
case None => Some(2)
case Some(x) => Some(-1)
}
map.updateWith("c") {
case None => Some(-1)
case Some(_) => None
}
assertEquals(map.get("b"), Some(2))
assertFalse(map.contains("c"))
}

}