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
}
}