Hi folks, newbie question :slightly_smiling_face: ...
# getting-started
a
Hi folks, newbie question 🙂 I was trying to implement a class that is backed by a Map. You can initialise it with a key and a value, and you can merge two together (but not with clashing keys) Problem is the the plus operator, since the constructor does not allow me to pass a map (since I don’t want to give an anaemic control from outside). Is there any trick I’m missing here? I was thinking to have a private constructor that only ControlledMap could use, but then again I have to use the primary constructor. The other alternative is to change table to be var and initialise a random ControlledMap and then swap the table property (but I’d hate doing that) Any suggestions?
Copy code
class ControlledMap(type: Type, index: Int) {
    private val table = mapOf(type to index)

    fun get(type: Type): Int =
        table.getOrElse(type) { throw IllegalArgumentException("Trying to get a non existing content from ControlledMap") }

    operator fun plus(other: ControlledMap): ControlledMap {
        if (table.keys.any { other.table.containsKey(it) }) {
            throw IllegalArgumentException("Cannot merge ControlledMaps with clashing keys")
        }


        // want to return a new ControlledMap where table is the union of the 2 tables (this.table + other.table)
    }


    enum class Type {
        A,
        B,
        C,
        D
    }
}
m
would this work for you?
a
this is exactly what I was looking for, thanks a lot! Haven’t thought about having the primary constructor private with table and public as secondary! thanks!
👋 1