Add infix fun to a class without extend the class

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.

The problem is discussed here: Compound extension - #14 by darksnake

Problem solved by using inline class.

inline class JObject(val json: JSONObject) {

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

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

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