簡體   English   中英

如果在父上下文中沒有此關鍵字,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 一起使用時中綴函數的行為還是我遺漏了什么?

這是按設計工作的。 來自關於中綴函數文檔

請注意,中綴函數總是需要指定接收者和參數。 當您使用中綴表示法在當前接收器上調用方法時,請明確使用它。 這是確保明確解析所必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM