#KT-1795 Fixed - added hashMap() and sortedMap() helper functions for creating maps more easily using tuples

This commit is contained in:
James Strachan
2012-04-16 12:00:47 +01:00
parent 376dc1cbaa
commit 0325e68a86
4 changed files with 62 additions and 12 deletions
+35 -2
View File
@@ -23,14 +23,47 @@ public inline fun hashSet<T>(vararg values: T) : HashSet<T> = values.to(HashSet<
/** Returns a new SortedSet with a variable number of initial elements */
public inline fun sortedSet<T>(vararg values: T) : TreeSet<T> = values.to(TreeSet<T>())
public inline fun <K,V> hashMap(): HashMap<K,V> = HashMap<K,V>()
/**
* Returns a new [[HashMap]] populated with the given tuple values where the first value in each tuple
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/MapTest.kt createUsingTuples
*/
public inline fun <K,V> hashMap(vararg values: #(K,V)): HashMap<K,V> {
val answer = HashMap<K,V>()
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v._1, v._2)
}
return answer
}
public inline fun <K,V> sortedMap(): SortedMap<K,V> = TreeMap<K,V>()
/**
* Returns a new [[SortedMap]] populated with the given tuple values where the first value in each tuple
* is the key and the second value is the value
*/
public inline fun <K,V> sortedMap(vararg values: #(K,V)): SortedMap<K,V> {
val answer = TreeMap<K,V>()
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v._1, v._2)
}
return answer
}
val Collection<*>.indices : IntRange
get() = 0..size-1
/**
* Converts the collection to an array
*/
public inline fun <T> java.util.Collection<T>.toArray() : Array<T> {
val answer = arrayOfNulls<T>(this.size)
var idx = 0
+9
View File
@@ -113,3 +113,12 @@ public inline fun <K,V,R,C: java.util.Map<K,R>> java.util.Map<K,V>.mapValuesTo(r
}
return result
}
/**
* Puts all the entries into the map with the first value in the tuple being the key and the second the value
*/
public inline fun <K,V> java.util.Map<K,V>.putAll(vararg values: #(K,V)): Unit {
for (v in values) {
put(v._1, v._2)
}
}