From c9959a10f9684f0ef10ac94bfecfc4eded6144f4 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Tue, 20 Dec 2011 18:06:58 +0000 Subject: [PATCH] added a couple of helper methods to Map to be able look up in a Map with function to provide a default value --- stdlib/ktSrc/JavaUtil.kt | 36 ++++++++++++++++++++++++++++++++++++ testlib/test/MapTest.kt | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 testlib/test/MapTest.kt diff --git a/stdlib/ktSrc/JavaUtil.kt b/stdlib/ktSrc/JavaUtil.kt index cae1b643c5c..b71427a49e0 100644 --- a/stdlib/ktSrc/JavaUtil.kt +++ b/stdlib/ktSrc/JavaUtil.kt @@ -195,3 +195,39 @@ val List.tail : T? val List.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 java.util.Map.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 java.util.Map.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 + } +} diff --git a/testlib/test/MapTest.kt b/testlib/test/MapTest.kt new file mode 100644 index 00000000000..ba0a9c4ee6d --- /dev/null +++ b/testlib/test/MapTest.kt @@ -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() + + 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()) + } +} \ No newline at end of file