Andrea Giuliano

10/10/2020, 5:46 PM
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?
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 {

Milan Hruban

10/10/2020, 5:58 PM
would this work for you?

Andrea Giuliano

10/10/2020, 6:38 PM
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