Skip to content

Instantly share code, notes, and snippets.

@ItsDoot
Last active July 1, 2018 20:14
Show Gist options
  • Save ItsDoot/cea87dff62634c2ffb707c04a93e5e68 to your computer and use it in GitHub Desktop.
Save ItsDoot/cea87dff62634c2ffb707c04a93e5e68 to your computer and use it in GitHub Desktop.
Map creation with only 1 extra object allocation.
/**
* Creates a HashMap with starter entries, with only 1 extra object allocation.
*/
inline fun <K, V> newHashMap(init: MapBuilder<K, V>.() -> Unit): HashMap<K, V> {
val builder = MapBuilder<K, V>()
builder.init()
return builder.map
}
class MapBuilder<K, V> {
val map = HashMap<K, V>()
inline infix fun K.at(value: V) {
map[this] = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment