11package dev.adamko.kxstsgen.util
22
3+ import kotlin.jvm.JvmName
34import kotlin.properties.ReadWriteProperty
45import kotlin.reflect.KProperty
56
@@ -9,14 +10,12 @@ class MutableMapWithDefaultPut<K, V>(
910 private val defaultValue : (key: K ) -> V ,
1011) : ReadWriteProperty<Any?, MutableMap<K, V>> {
1112
12- private var map: MutableMap <K , V > = with (initial.toMutableMap()) {
13- withDefault { key -> getOrPut(key) { defaultValue(key) } }
14- }
13+ private var map: MutableMap <K , V > = initial.toMutableMap().withDefaultPut(defaultValue)
1514
1615 override fun getValue (thisRef : Any? , property : KProperty <* >): MutableMap <K , V > = map
1716
1817 override fun setValue (thisRef : Any? , property : KProperty <* >, value : MutableMap <K , V >) {
19- this .map = value
18+ this .map = value.withDefaultPut(defaultValue)
2019 }
2120}
2221
@@ -33,6 +32,20 @@ class MapWithDefaultPut<K, V>(
3332 override fun getValue (thisRef : Any? , property : KProperty <* >): Map <K , V > = map
3433
3534 override fun setValue (thisRef : Any? , property : KProperty <* >, value : Map <K , V >) {
36- this .map = value
35+ this .map = value.toMutableMap().withDefaultPut(defaultValue)
3736 }
3837}
38+
39+
40+ @JvmName(" mapWithDefaultPut" )
41+ fun <K , V > Map <K , V >.withDefaultPut (defaultValue : (key: K ) -> V ): Map <K , V > =
42+ with (this .toMutableMap()) {
43+ withDefault { key -> getOrPut(key) { defaultValue(key) } }
44+ }
45+
46+
47+ @JvmName(" mutableMapWithDefaultPut" )
48+ fun <K , V > MutableMap <K , V >.withDefaultPut (defaultValue : (key: K ) -> V ): MutableMap <K , V > =
49+ with (this ) {
50+ withDefault { key -> getOrPut(key) { defaultValue(key) } }
51+ }
0 commit comments