added a couple of helper methods to Map to be able look up in a Map with function to provide a default value

This commit is contained in:
James Strachan
2011-12-20 18:06:58 +00:00
parent c3b41a5931
commit c9959a10f9
2 changed files with 71 additions and 0 deletions
+36
View File
@@ -195,3 +195,39 @@ val <T> List<T>.tail : T?
val <T> List<T>.last : T?
get() = this.tail
// Map APIs
/** Returns the size of the map */
/* TODO get redeclaration errors
val Map<*,*>.size : Int
get() = size()
*/
/** Returns true if this map is empty */
/* TODO get redeclaration errors
val Map<*,*>.empty : Boolean
get() = isEmpty()
*/
/** Returns the value for the given key or returns the result of the defaultValue function if there was no entry for the given key */
inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: fun(): V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
return defaultValue()
}
}
/** Returns the value for the given key or the result of the defaultValue function is put into the map for the given value and returned */
inline fun <K,V> java.util.Map<K,V>.getOrElseUpdate(key: K, defaultValue: fun(): V) : V {
val current = this.get(key)
if (current != null) {
return current
} else {
val answer = defaultValue()
this.put(key, answer)
return answer
}
}
+35
View File
@@ -0,0 +1,35 @@
namespace test.collections
import std.test.*
// TODO can we avoid importing all this stuff by default I wonder?
// e.g. making println and the collection builder methods public by default?
import std.*
import std.io.*
import std.util.*
import java.util.*
class MapTest() : TestSupport() {
val data = HashMap<String, Int>()
fun testGetOrElse() {
val a = data.getOrElse("foo"){2}
assertEquals(2, a)
val b = data.getOrElse("foo"){3}
assertEquals(3, b)
// TODO should be able to miss the () off of size
assertEquals(0, data.size())
}
fun testGetOrElseUpdate() {
val a = data.getOrElseUpdate("foo"){2}
assertEquals(2, a)
val b = data.getOrElseUpdate("foo"){3}
assertEquals(2, b)
assertEquals(1, data.size())
}
}