Karlo Lozovina
08/31/2020, 11:25 AMvar f = fooMap["key"]
f = f+1
Michael de Kaste
08/31/2020, 11:49 AMmap.computeIfPresent(3.0) { key: Double, value: Int ->
value + 1
}
Karlo Lozovina
08/31/2020, 11:56 AMNikky
08/31/2020, 12:38 PMMutableMap.MutableEntry<K,V>
val hashmap = mutableMapOf("key" to 1)
val entry = hashmap.entries.find { it.key == "key" }!!
val oldValue = entry.setValue(2)
println("oldValue: $oldValue") // oldValue: 1
println("map: $hashmap") // map: {key=2}
but i don't think you should
if the key is known you can also do
var key by hashmap
println("map: $hashmap") // map: {key=2}
key = 3
println("map: $hashmap") // map: {key=3}
the last bit works on all mutable maps via extensions in MapAccesorsKt
Karlo Lozovina
08/31/2020, 1:17 PMMutableEntry
is interesting, might simplify some code... btw, is it possible to get somethin similar to a MutableEntry but for a class property thats Int or Double?Matteo Mirk
08/31/2020, 2:12 PMclass Mutable {
var i:Int = 0
}
val m = Mutable()
m.i = 1
println(m.i) // 1
If you need to introspect on a class like you wanted to do on maps, you have to use reflection, for example:
class C(val a: Int, var b: Double)
fun main() {
val c = C(0, 0.0)
val propB = C::class.declaredMemberProperties
.find { it.name == "b" } as KProperty1<C, Double>?
if (propB is KMutableProperty1) {
propB.set(c, 3.14)
println(c.b)
}
}
but I don’t know honestly what you’re getting into… what is that you’re trying to achieve?Karlo Lozovina
08/31/2020, 6:13 PMvar x = m.i
x = 1000
// m.i is also 1000 now
Karlo Lozovina
08/31/2020, 6:13 PMKarlo Lozovina
08/31/2020, 6:14 PMNikky
08/31/2020, 6:30 PMvar x by m::i
and modifying x
will modify m.i
Karlo Lozovina
08/31/2020, 6:35 PMKarlo Lozovina
08/31/2020, 6:35 PMNikky
08/31/2020, 6:50 PM::property
gives you a KProperty
or KMutablePRoperty
and these extension functions exist in the stdlib: https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/properties/PropertyReferenceDelegates.kt
at least i think that is how this works