Reputation: 942
Assume I have this property in a class:
private var dates: Map<String, Long?> = mapOf(
"creation" to System.currentTimeMillis(),
"lastUpdate" to System.currentTimeMillis()
)
Now, I need to update "lastUpdate" timestamp using function below:
fun start(): Boolean {
this.dates["lastUpdate"] = System.currentTimeMillis()
return true
}
I get this Error:
"No set method providing array access"
How should I define setter and getter methods for maps?
Upvotes: 0
Views: 513
Reputation: 8096
Kotlin's Map is immutable, i.e. you neither can edit any values in it nor you can add any new values.
In Kotlin there is seperate interface that does give you operator fun get()
and operator fun set()
in it, it is actually a MutableMap, an extension to the Map
.
You can create MutableMap using the mutableMapOf function in the standard library.
private var dates: MutableMap<String, Long?> = mutableMapOf(
"creation" to System.currentTimeMillis(),
"lastUpdate" to System.currentTimeMillis()
)
// Then change whatever you want to
dates["lastUpdate"] = System.currentTimeMillis()
Upvotes: 5