在lambda中使用接收者的中缀函数(对于DSL)

我正在使用Kotlin创建一个DSL,并且我希望利用带有中缀函数的接收器对象来获得这种常规的DSL感觉。 我将从下面的语法例子开始:

myDslFunction {myReceiversInfixFunc“一些字符串”}

我的计划是这样的代码:

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 } } 

上面的函数和类片段编译得很好,但是上面列出的DSL语法没有。 以下是我编写的用于测试编译的一些测试函数:

 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 } } 

这里的主要区别在于添加了this关键字来设置中缀表示法,但是我建议这是不受欢迎的,并且会破坏使用接收器对象的目的。

有什么明显的我在这里失踪? 我能达到我想要的语法吗? 如果我忽略Kotlin公约来协助这样做,我不会感到惊讶…

你不能实现这个语法,因为Kotlin只支持显式指定接收者的中infix函数调用: this myReceiversInfixFunc "someString"

这个语法有一个(很老的)语言特性请求: KT-1292 。