|
| 1 | + |
| 2 | + |
| 3 | + |
| 4 | +import scala.math.Ordering |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +/** The heart of the problem - we want to retain the ordering when |
| 9 | + * using `++` on sorted maps. |
| 10 | + * |
| 11 | + * There are 2 `++` overloads - a generic one in traversables and |
| 12 | + * a map-specific one in `MapLike` - which knows about the ordering. |
| 13 | + * |
| 14 | + * The problem here is that the expected return type for the expression |
| 15 | + * in which `++` appears drives the decision of the overload that needs |
| 16 | + * to be taken. |
| 17 | + * The `collection.SortedMap` does not have `++` overridden to return |
| 18 | + * `SortedMap`, but `immutable.Map` instead. |
| 19 | + * This is why `collection.SortedMap` used to resort to the generic |
| 20 | + * `TraversableLike.++` which knows nothing about the ordering. |
| 21 | + * |
| 22 | + * To avoid `collection.SortedMap`s resort to the more generic `TraverableLike.++`, |
| 23 | + * we override the `MapLike.++` overload in `collection.SortedMap` to return |
| 24 | + * the proper type `SortedMap`. |
| 25 | + */ |
| 26 | +object Test { |
| 27 | + |
| 28 | + def main(args: Array[String]) { |
| 29 | + testCollectionSorted() |
| 30 | + testImmutableSorted() |
| 31 | + } |
| 32 | + |
| 33 | + def testCollectionSorted() { |
| 34 | + import collection._ |
| 35 | + val order = implicitly[Ordering[Int]].reverse |
| 36 | + var m1: SortedMap[Int, String] = SortedMap.empty[Int, String](order) |
| 37 | + var m2: SortedMap[Int, String] = SortedMap.empty[Int, String](order) |
| 38 | + |
| 39 | + m1 += (1 -> "World") |
| 40 | + m1 += (2 -> "Hello") |
| 41 | + |
| 42 | + m2 += (4 -> "Bar") |
| 43 | + m2 += (5 -> "Foo") |
| 44 | + |
| 45 | + val m3: SortedMap[Int, String] = m1 ++ m2 |
| 46 | + |
| 47 | + println(m1) |
| 48 | + println(m2) |
| 49 | + println(m3) |
| 50 | + |
| 51 | + println(m1 + (3 -> "?")) |
| 52 | + } |
| 53 | + |
| 54 | + def testImmutableSorted() { |
| 55 | + import collection.immutable._ |
| 56 | + val order = implicitly[Ordering[Int]].reverse |
| 57 | + var m1: SortedMap[Int, String] = SortedMap.empty[Int, String](order) |
| 58 | + var m2: SortedMap[Int, String] = SortedMap.empty[Int, String](order) |
| 59 | + |
| 60 | + m1 += (1 -> "World") |
| 61 | + m1 += (2 -> "Hello") |
| 62 | + |
| 63 | + m2 += (4 -> "Bar") |
| 64 | + m2 += (5 -> "Foo") |
| 65 | + |
| 66 | + val m3: SortedMap[Int, String] = m1 ++ m2 |
| 67 | + |
| 68 | + println(m1) |
| 69 | + println(m2) |
| 70 | + println(m3) |
| 71 | + |
| 72 | + println(m1 + (3 -> "?")) |
| 73 | + } |
| 74 | +} |
0 commit comments