I could not reproduce the stack overflow, but here is what happens:
override def filterKeys(p: A => Boolean): Map[A, B] = new DefaultMap[A, B] { override def foreach[C](f: ((A, B)) => C): Unit = for (kv <- self) if (p(kv._1)) f(kv) def iterator = self.iterator.filter(kv => p(kv._1)) override def contains(key: A) = self.contains(key) && p(key) def get(key: A) = if (!p(key)) None else self.get(key) }
Note that copying the values does not occur: the new class simply adds rules to the four methods that will change the way they work to reflect the added filter. Since you reapply filterKeys
(10,000 times), this means that you have 10,000 classes, each of which points to the previous one, and the first points to the original map.
When you call one of the above methods (directly or indirectly) in the final class, 10,000 nested methods will be called, which can lead to a stack overflow if your stack is small enough.
source share