renamed the rather long getOrElseUpdate to a simpler getOrPut which is a bit simpler and more accurate; as a new entry is put into the Map if its null

This commit is contained in:
James Strachan
2012-02-21 11:11:43 +00:00
parent 724f7860ab
commit a68b00dfd4
4 changed files with 8 additions and 7 deletions
+1 -1
View File
@@ -110,7 +110,7 @@ inline fun <T> java.lang.Iterable<T>.foldRight(initial: T, operation: (it: T, it
inline fun <T,K> java.lang.Iterable<T>.groupBy(result: Map<K,List<T>> = HashMap<K,List<T>>(), toKey: (T)-> K) : Map<K,List<T>> {
for (elem in this) {
val key = toKey(elem)
val list = result.getOrElseUpdate(key){ ArrayList<T>() }
val list = result.getOrPut(key){ ArrayList<T>() }
list.add(elem)
}
return result
+3 -2
View File
@@ -19,8 +19,9 @@ inline fun linkedList<T>(vararg values: T) : LinkedList<T> = values.to(LinkedLi
/** Returns a new HashSet with a variable number of initial elements */
inline fun hashSet<T>(vararg values: T) : HashSet<T> = values.to(HashSet<T>(values.size))
/** Returns a new hash map */
inline fun <K,V> hashMap() = HashMap<K,V>()
inline fun <K,V> hashMap(): HashMap<K,V> = HashMap<K,V>()
inline fun <K,V> sortedMap(): SortedMap<K,V> = TreeMap<K,V>()
val Collection<*>.indices : IntRange
+1 -1
View File
@@ -41,7 +41,7 @@ inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V
}
/** 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: ()-> V) : V {
inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
val current = this.get(key)
if (current != null) {
return current
+3 -3
View File
@@ -21,11 +21,11 @@ class MapTest() : TestSupport() {
assertEquals(0, data.size)
}
fun testGetOrElseUpdate() {
val a = data.getOrElseUpdate("foo"){2}
fun testGetOrPut() {
val a = data.getOrPut("foo"){2}
assertEquals(2, a)
val b = data.getOrElseUpdate("foo"){3}
val b = data.getOrPut("foo"){3}
assertEquals(2, b)
assertEquals(1, data.size())