Had to make this today. It's a map that holds diff...
# random
y
Had to make this today. It's a map that holds different values, where each key determines the type of the value. May be useful for somebody out there!
Copy code
private class TypedMutableMap private constructor(private val map: MutableMap<Key<*>, Any?>) {
  constructor() : this(mutableMapOf())
  interface Key<T>
  @Suppress("UNCHECKED_CAST")
  operator fun <T> get(key: Key<T>): T = map.getValue(key) as T
  operator fun <T> set(key: Key<T>, value: T) {
    map[key] = value
  }
  fun copy(): TypedMutableMap = TypedMutableMap(map.toMutableMap())
}
This can be made into a
value class
, I just didn't have the need to do so
👍 2
k
Was it a deliberate decision not to implement the
Map
or
MutableMap
interface or did you just not have a need for it?
y
I don't see how I'd do it. At least, in any useful way. I can implement
Map<Key<*>, Any?>
, but that's hardly useful. I don't think I can implement
MutableMap
in any useful way
k
I thought it might be useful as it gives you numerous
Map
features, such as
values()
, which might be useful if you don't care about the exact types but just want a set of values.
👍🏼 1
c
tried with delegation. only thing I could not figure out is the
get
to be typed.
Copy code
class TypedMutableMap private constructor(
    map: MutableMap<Key<*>, Any?>,
) : MutableMap<TypedMutableMap.Key<*>, Any?> by map {
    constructor() : this(mutableMapOf())

    interface Key<T>

    operator fun <T> get(key: Key<T>): T = this.getValue(key) as T

    operator fun <T> set(
        key: Key<T>,
        value: T,
    ) {
        this.put(key, value)
    }

    fun copy(): TypedMutableMap = TypedMutableMap(toMutableMap())
}
so technically its still a mutable map.
Copy code
e: file:///com/cmgapps/compose/Main.kt:44:5 Platform declaration clash: The following declarations have the same JVM signature (get(Lcom/cmgapps/compose/TypedMutableMap$Key;)Ljava/lang/Object;):
    fun get(key: TypedMutableMap.Key<*>): Any? defined in com.cmgapps.compose.TypedMutableMap
    fun <T> get(key: TypedMutableMap.Key<T>): T defined in com.cmgapps.compose.TypedMutableMap