Reputation: 60321
In the documentation, I see we have setValue
for a mutableMap.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/set-value.html
operator fun <V> MutableMap<in String, in V>.setValue(
thisRef: Any?,
property: KProperty<*>,
value: V)
However when try using it, it doesn't seem to exist. (I'm using Kotlin 1.3)
val a = mutableMapOf(1 to 1, 2 to 3)
a.setValue(...) // error out
Is it not available anymore?
Upvotes: 2
Views: 3009
Reputation: 60321
To provide further context of my finding on how to use setValue
directly, created an example below.
data class Something(val boo: String? = null)
@Test
fun testSetValue() {
// Showing auto delegate value of foo, which uses
// setValue under the hood to extract 1000 for foo
val foo: Int by mutableMapOf("foo" to 1000)
println(foo) // 1000
// Demonstrating setValue ussage directly setting boo value
val x = mutableMapOf("abc" to 1)
x.setValue(null, Something::boo, 200)
println(x) // {abc=1, boo=200}
// Similarly for `getValue`
println(x.getValue(null, Something::boo) // 200
}
Upvotes: 0
Reputation: 89668
This is an extension that implements the setValue
method required on a type for it to be used as a proprety delegate. The official documentation covers how Maps can be used as delegates here: Storing Properties in a Map.
TLDR, you get to use this kind of syntax, delegating properties into a Map instance:
class User(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
If you want to simply set values of a MutableMap
, use the set
method, also available as the []
operator:
val map = mutableMapOf(1 to 1, 2 to 3)
map.set(2, 2)
map[2] = 2
Or the put
method, which also returns the previous value stored by the key you modified:
val oldValue: Int = map.put(2, 5)
Upvotes: 5