is it possible to get a "reference" to a HashMap e...
# announcements
k
is it possible to get a "reference" to a HashMap entry? something so that I can write something like this:
Copy code
var f = fooMap["key"]
f = f+1
🚫 3
m
no, properties of a map are immutable and need to be reinserted after modification. What you could do is call the helper functions like:
Copy code
map.computeIfPresent(3.0) { key: Double, value: Int ->
        value + 1
    }
k
Thanks
n
you can get the reference to a
MutableMap.MutableEntry<K,V>
Copy code
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
Copy code
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
☝️ 1
k
oh, this
MutableEntry
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?
m
if your class has a mutable property you just use standard syntax:
Copy code
class 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:
Copy code
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?
k
I was thinking more like (from your example)
Copy code
var x = m.i
x = 1000
// m.i is also 1000 now
I know that doesn't work, but I was wondering if there was some syntax to get a "reference" to an Int field...
(I'm mostly porting something from Rust, so obviously lot's of patterns don't translate directly, I'm just messing around)
n
you can do this
Copy code
var x by m::i
and modifying
x
will modify
m.i
1
k
oh, cool! didn't know about that feature... I did come across delegation, that's it?
how does that excatly work?
n
::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
👍 2