https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dan

12/27/2020, 1:41 AM
I have a small problem to solve. I need a data structure similar to map but it only allows to assign value the first time. I understood that I could create a customise Map class but I am looking for a shorter way from built int library. Ex:
Copy code
m = mutableMapOf<String, Int>()
m.put("a", 1)
m.put("a", 1) // throw exception here
r

Ruckus

12/27/2020, 2:27 AM
Copy code
class OneMap<K, V> {
    private val values = mutableMapOf<K, V>()
    operator fun get(key: K) = values[key]
    operator fun set(key: K, value: V) {
        require(key !in values)
        values[key] = value
    }
}

fun main() {
    val m = OneMap<String, Int>()
	m["a"] = 1
	m["a"] = 1 // throw exception here
}
If you need more features from a map, implement them, or just implement the
MutableMap
interface.
d

dan

12/27/2020, 5:33 AM
Thanks @Ruckus. This saves my laziness.
2 Views