Add infix fun to a class without extend the class


#1
class JObject : JSONObject() {

    inline infix operator fun String.invoke(obj: JObject.() -> Unit) {
        put(this, JObject().apply(obj))
    }

    infix fun String.to(value: Any) {
        put(this, value)
    }
}


inline fun jsonObj(builder: JObject.() -> Unit): JSONObject {
    return JObject().apply(builder)
}

image

My question is how to add infix function to JSONObject directly without extends it. The subclass does nothing in this case.

There is only one ‘this’.

Anko library have same problem, extends every ViewGroup, and add inline method only to subclass.


#2

The problem is discussed here: Compound extension