Skip to content

Commit 273e549

Browse files
authored
Merge pull request scala#9957 from som-snytt/tweak/11894-overwrought
2 parents cd6cd30 + e6c9464 commit 273e549

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/library/scala/collection/convert/JavaCollectionWrappers.scala

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import java.util.{concurrent => juc}
1818
import java.{lang => jl, util => ju}
1919

2020
import scala.jdk.CollectionConverters._
21+
import scala.util.chaining._
2122

2223
/** Wrappers for exposing Scala collections as Java collections and vice-versa */
2324
@SerialVersionUID(3L)
@@ -334,17 +335,34 @@ private[collection] object JavaCollectionWrappers extends Serializable {
334335
def subtractOne(key: K): this.type = { underlying remove key; this }
335336

336337
// support Some(null) if currently bound to null
337-
override def put(k: K, v: V): Option[V] = {
338-
val present = underlying.containsKey(k)
339-
val result = underlying.put(k, v)
340-
if (present) Some(result) else None
341-
}
338+
override def put(k: K, v: V): Option[V] =
339+
if (v == null) {
340+
val present = underlying.containsKey(k)
341+
val result = underlying.put(k, v)
342+
if (present) Some(result) else None
343+
} else {
344+
var result: Option[V] = None
345+
def recompute(k0: K, v0: V): V = v.tap(_ =>
346+
if (v0 != null) result = Some(v0)
347+
else if (underlying.containsKey(k0)) result = Some(null.asInstanceOf[V])
348+
)
349+
underlying.compute(k, recompute)
350+
result
351+
}
342352

343353
override def update(k: K, v: V): Unit = underlying.put(k, v)
344354

345355
// support Some(null) if currently bound to null
346-
override def remove(k: K): Option[V] =
347-
if (underlying.containsKey(k)) Some(underlying.remove(k)) else None
356+
override def remove(k: K): Option[V] = {
357+
var result: Option[V] = None
358+
def recompute(k0: K, v0: V): V = {
359+
if (v0 != null) result = Some(v0)
360+
else if (underlying.containsKey(k0)) result = Some(null.asInstanceOf[V])
361+
null.asInstanceOf[V]
362+
}
363+
underlying.compute(k, recompute)
364+
result
365+
}
348366

349367
def iterator: Iterator[(K, V)] = new AbstractIterator[(K, V)] {
350368
val ui = underlying.entrySet.iterator

0 commit comments

Comments
 (0)