I am writing a sample DSL to create an infra-as-code library. The basic structure would be as below:
class Employee internal constructor (private val init: Employee.() -> Unit) {
var name:String = ""
var address:String = ""
infix fun showMessage(msg:String) =
println("${this.name} resides at ${this.address} and wishes you $msg")
internal fun describe(){
init()
//initialization
}
}
fun employee(process:Employee.()->Unit) = Employee(process).describe()
fun main(){
employee {
name="John Doe"
address="Amsterdam"
this showMessage "happy new year"
// showMessage("This works")
}
}
I am thinking that showMessage infix function should work as other infix inside the Employee context but i need to use this
to make it work as an infix.
The function invocation works well in the context without this.
Is this the behaviour of infix functions while using along with DSL or am i missing something?
This is working as designed. From the docs on infix functions:
Note that infix functions always require both the receiver and the parameter to be specified. When you're calling a method on the current receiver using the infix notation, use this explicitly. This is required to ensure unambiguous parsing.