Extend a function to add parameters? (for Type-Safe Builders)


#1

I use Type-Safe Builders (TSB) to create a DSL that generates XML. The TSB uses functions to create elements (here: XML tags) with parameters for the attributes. My XML contains many types of tags, that have the same attributes. This would result in many functions sharing a set of the same types of parameters.

Is it possible to create a function and specify a set of parameters without writing them all down? Inherit a function?
At the above link there is the function a.
It is used like

a(href = "http://kotlinlang.org")

The corresponding function is

fun a(href: String, init: A.() -> Unit) {
    val a = initTag(A(), init)
    a.href = href
}

I want to use

b(href = "http://kotlinlang.org", attr = "something")

With a function like this

fun b(attr: String, init: B.() -> Unit){
    val b= initTag(B(), init)
    b.attr = attr
    //use href here or just have it set automatically, maybe like:
    b.href = superFun.href
}

so I don’t need to repeat the parameter href for every function (XML tag) that has this attribute. Can this be achieved somehow?
Could Reflection or Function Composition help in this case? I played with Function Composition a little, but to no avail so far.

(I am new to Kotlin)
Thanks in advance :slight_smile: