Accessing interface delegate

I tried to ‘extend’ mutableMapOf() by using delegation. The problem is that I can’t access the delegate object to call Any methods, especially toString(). Something like MutableMap.super.

Is there a way?

Snippet:

class MutableMapEx<K, V>: MutableMap<K, V> by mutableMapOf<K, V>(){
    override fun toString(): String {
        return entries.toString()
    }

    inline infix fun K.eq(v: V) {
        this@MutableMapEx.put(this, v)
    }
}

inline fun <reified  K, reified V> map(f: MutableMapEx<K, V>.() -> Unit): Map<K, V> {
    val map = MutableMapEx<K, V>()
    map.f()
    return map
}

fun main(args: Array<String>) {
    val m = map<String, Int> {
        "X" eq 1
        "Y" eq 2
    }

    println(m)
}

I found it!

Solved by using explicit val as delegate.

class MutableMapEx<K, V> private constructor(private val mmap: MutableMap<K, V>): MutableMap<K, V> by mmap {

    constructor() : this(mutableMapOf<K, V>())

    override fun toString(): String {
        return mmap.toString()
    }

    inline infix fun K.eq(v: V) {
        this@MutableMapEx.put(this, v)
    }
}

inline fun <reified  K, reified V> map(f: MutableMapEx<K, V>.() -> Unit): Map<K, V> {
    val map = MutableMapEx<K, V>()
    map.f()
    return map
}

fun main(args: Array<String>) {
    val m = map<String, Int> {
        "X" eq 1
        "Y" eq 2
    }

    println(m)
}
1 Like