如果父上下文中没有此关键字,Kotlin DSL 中的中缀函数将无法工作
Infix function in Kotlin DSL does not work without this keyword in parent context
我正在编写示例 DSL 来创建基础设施即代码库。基本结构如下:
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")
}
}
我认为 showMessage 中缀函数应该像 Employee 上下文中的其他中缀一样工作,但我需要使用 this
使其作为中缀工作。
函数调用在没有 this 的上下文中运行良好。
这是与 DSL 一起使用时中缀函数的行为还是我遗漏了什么?
这是按设计工作的。来自 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.
我正在编写示例 DSL 来创建基础设施即代码库。基本结构如下:
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")
}
}
我认为 showMessage 中缀函数应该像 Employee 上下文中的其他中缀一样工作,但我需要使用 this
使其作为中缀工作。
函数调用在没有 this 的上下文中运行良好。
这是与 DSL 一起使用时中缀函数的行为还是我遗漏了什么?
这是按设计工作的。来自 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.