viralshah
04/06/2020, 6:37 PMShawn
04/06/2020, 6:44 PMviralshah
04/06/2020, 6:44 PMviralshah
04/06/2020, 6:45 PMShawn
04/06/2020, 6:45 PMtoX()
will basically no-op if you’re trying to convert to a type it already isShawn
04/06/2020, 6:45 PMShawn
04/06/2020, 6:45 PMShawn
04/06/2020, 6:46 PMMap
and not MutableMap
, there’s an implicit understanding that you’re not going to try to mutate the map you’ve been givenShawn
04/06/2020, 6:47 PMMap
to its underlying (probably mutable) type, but that’s an anti-pattern and you can’t really sanely guard against every instance where someone might do something like thatShawn
04/06/2020, 6:49 PMviralshah
04/06/2020, 6:59 PMnkiesel
04/06/2020, 7:51 PMval m = mapOf("a" to "A", "b" to 2)
fun f1(m: Map<String, Any>) {
val m2 = m.toMutableMap()
m2["c"] = "C"
println(m2)
}
fun f2(m: Map<String, Any>) {
val m2 = m.toMutableMap()
m2["d"] = 4L
println(m2)
}
println(m)
f1(m)
f2(m)
Something like this?viralshah
04/06/2020, 7:52 PMnkiesel
04/06/2020, 7:53 PMfun f2(m: Map<String, Any>) {
val m2 = mapOf("d" to 4L)
println(m + m2)
}
is another optionviralshah
04/06/2020, 8:05 PMrocketraman
04/06/2020, 9:50 PMfun mutateMap1(m: MutableMap<String, Any>) {
m["c"] = "C"
println(m)
}
The caller can then wrap all the calls to these functions inside a buildMap
function (1.3.70+), or similarly encapsulated logic.viralshah
04/06/2020, 9:51 PMrocketraman
04/06/2020, 9:55 PMval m = buildMap<String, Any> {
mapFn1(this)
mapFn2(this)
...
}
If your functions are lambdas in a list or part of an interface or something you can of course just invoke them all inside the builder in one line.viralshah
04/06/2020, 9:55 PMrocketraman
04/06/2020, 9:56 PMMutableMap
receiver like this:
fun MutableMap<String, Any>.fn1() {
this["c"] = "C"
println(this)
}
then you can call them like this:
val m = buildMap<String, Any> {
fn1()
fn2()
...
}
rocketraman
04/06/2020, 10:10 PMval mutations: List<(MutableMap<String, Any>) -> Unit> = ...
then you can build the map like this:
val m = buildMap<String, Any> {
mutations.forEach { apply(it) }
}
rocketraman
04/06/2020, 10:12 PMprintln
from each function and put that in the builder forEach
instead.