From 81d83cd4f07a53fe3ccff71897334a2c11a3d8c4 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Fri, 14 Sep 2012 11:18:35 +0100 Subject: [PATCH] added component1() / component2() methods to Map.Entry along with a test case so that maps can be iterated over via: for ((k, v) in map) --- libraries/stdlib/src/kotlin/Maps.kt | 10 ++++++++++ libraries/stdlib/test/MapTest.kt | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/libraries/stdlib/src/kotlin/Maps.kt b/libraries/stdlib/src/kotlin/Maps.kt index 0f51a8c77ab..acc6f594b82 100644 --- a/libraries/stdlib/src/kotlin/Maps.kt +++ b/libraries/stdlib/src/kotlin/Maps.kt @@ -29,6 +29,16 @@ val Map.Entry.key : K val Map.Entry.value : V get() = getValue().sure() +/** Returns the key of the entry */ +fun Map.Entry.component1() : K { + return getKey().sure() +} + +/** Returns the value of the entry */ +fun Map.Entry.component2() : V { + return getValue().sure() +} + /** * Returns the value for the given key or returns the result of the defaultValue function if there was no entry for the given key * diff --git a/libraries/stdlib/test/MapTest.kt b/libraries/stdlib/test/MapTest.kt index 8c4228510bb..f0ea77fdf6e 100644 --- a/libraries/stdlib/test/MapTest.kt +++ b/libraries/stdlib/test/MapTest.kt @@ -80,6 +80,23 @@ class MapTest { assertEquals("beverage,beer,location,Mells,name,James", list.makeString(",")) } + test fun iterateWithExtraction() { + val map = TreeMap() + map["beverage"] = "beer" + map["location"] = "Mells" + map["name"] = "James" + + val list = arrayList() + for ((key, value) in map) { + println("key = ${key}, value = ${value}") + list.add(key) + list.add(value) + } + + assertEquals(6, list.size()) + assertEquals("beverage,beer,location,Mells,name,James", list.makeString(",")) + } + test fun map() { val m1 = TreeMap() m1["beverage"] = "beer"