Reputation: 42849
I'm working on creating a DSL using Kotlin, and I was hoping to utilize a receiver object with an infix function to get that groovy DSL feeling. I will start with an example of the syntax I am after:
myDslFunction { myReceiversInfixFunc "some string" }
My plan for achieving this was this code:
fun myDslFunction(builderFunction: MyReceiverObject.() -> Unit) {
val receiver = MyReceiverObject()
builderFunction(receiver)
// do something with receiver
}
class MyReceiverObject {
infix fun myReceiversInfixFunc(someString: String) {
// do something with someString
}
}
The function and class snippets above compiles fine, but the DSL syntax listed above doesn't. Here are some test functions I wrote to test the compilation:
fun test() {
// desired syntax
myDslFunction {
myReceiversInfixFunc "some string" // doesn't compile
}
// not-desired syntax that compiles and works...
myDslFunction {
this myReceiversInfixFunc "some string" // does compile
}
}
The key difference here is the addition of the this
keyword to setup the infix notation, but I would suggest that is undesired, and defeats the purpose of using the receiver object.
Is there something obvious I am missing here? Can I achieve my desired syntax? I wouldn't be surprised if I am overlooking a Kotlin convention to assist with doing this...
Upvotes: 3
Views: 802