Skip to content

Commit

Permalink
scala.collection.Map.foreachEntry backport for 2.11/2.12
Browse files Browse the repository at this point in the history
Fixes #335.
  • Loading branch information
ijuma committed Jun 5, 2020
1 parent c828122 commit 5ff4188
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ private[compat] trait PackageShared {
type IterableOnce[+X] = c.TraversableOnce[X]
val IterableOnce = c.TraversableOnce

implicit def toMapExtensionMethods[K, V](
self: scala.collection.Map[K, V]): MapExtensionMethods[K, V] =
new MapExtensionMethods[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 @@ -393,6 +397,14 @@ class Tuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2](
new Tuple3Zipped((self.colls._1, self.colls._2, t3))
}

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

def foreachEntry[U](f: (K, V) => U): Unit = {
self.foreach { case (k, v) => f(k, v) }
}

}

class MapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
private val self: IterableView[(K, V), C])
extends AnyVal {
Expand Down
29 changes: 29 additions & 0 deletions compat/src/test/scala/test/scala/collection/MapTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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._

class MapTest {

@Test
def foreachEntry: Unit = {
val map = Map("a" -> 1, "b" -> 2, "c" -> 3)
var copy = Map.empty[String, Int]
map.foreachEntry((k, v) => copy += k -> v)
assertEquals(map, copy)
}

}

0 comments on commit 5ff4188

Please sign in to comment.