lib: add `provide_default_value` in Map to allow subclasses to provide
authorJean Privat <jean@pryen.org>
Tue, 4 Mar 2014 17:03:06 +0000 (12:03 -0500)
committerJean Privat <jean@pryen.org>
Wed, 5 Mar 2014 15:32:25 +0000 (10:32 -0500)
specific behavior when there is no value associated with a key.

The default behavior is to abort, as usual.

Basically this patch factorizes the `abort` in a single function that can
be redefined.

Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/collection/abstract_collection.nit
lib/standard/collection/array.nit
lib/standard/collection/hash_collection.nit

index c86c748..18bac96 100644 (file)
@@ -322,6 +322,13 @@ interface MapRead[K: Object, E]
 
        # Number of items in the collection.
        fun length: Int is abstract
+
+       # Called by the underling implementation of `[]` to provide a default value when a `key` has no value
+       # By default the behavior is to abort.
+       #
+       # Note: the value is returned *as is*, implementations may want to store the value in the map before returning it
+       # @toimplement
+       protected fun provide_default_value(key: K): E do abort
 end
 
 # Maps are associative collections: `key` -> `item`.
@@ -545,7 +552,7 @@ interface CoupleMap[K: Object, E]
        do
                var c = couple_at(key)
                if c == null then
-                       abort
+                       return provide_default_value(key)
                else
                        return c.second
                end
index 073471e..988ddbf 100644 (file)
@@ -453,7 +453,7 @@ class ArrayMap[K: Object, E]
                if i >= 0 then
                        return _items[i].second
                else
-                       abort
+                       return provide_default_value(key)
                end
        end
 
index 7f73c3b..f668379 100644 (file)
@@ -208,7 +208,7 @@ class HashMap[K: Object, V]
        do
                var c = node_at(key)
                if c == null then
-                       abort
+                       return provide_default_value(key)
                else
                        return c._value
                end