Skip to content

Instantly share code, notes, and snippets.

@BomBardyGamer
Created March 31, 2021 15:44
Show Gist options
  • Save BomBardyGamer/0648f5e665ebebf0a190151e914939e3 to your computer and use it in GitHub Desktop.
Save BomBardyGamer/0648f5e665ebebf0a190151e914939e3 to your computer and use it in GitHub Desktop.
Bardy's Kotlin collection extensions
// Takes a Map<K, V> and applies the given function to each one of its elements, returning a new
// Map<K1, V1> with the transformed key-value pairs
fun <K, V, K1, V1> Map<K, V>.transform(function: (Map.Entry<K, V>) -> Pair<K1, V1>): Map<K1, V1> {
val temp = mutableMapOf<K1, V1>()
for (entry in this) {
temp += function(entry)
}
return temp
}
// Mirror of Kotlin's sumBy that uses longs instead of integers
fun <T> Iterable<T>.sumBy(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment