簡體   English   中英

隱式接收器無法在此上下文中調用單元

[英]Unit can't be called in this context by implicit receiver

我正在關注這個 Kotlin 示例( https://www.jetbrains.com/help/teamcity/kotlin-dsl.html#Editing+Kotlin+DSL ),並嘗試為 myZ4FBA3BC02B72582EE9A6867A1E 腳本

這是我的代碼片段

steps {
    script {
        name = "Style check"
        id("StyleCheck")
        enabled = false
        scriptContent = """
            #!/bin/bash

            make docker run="make ci lint"
        """.trimIndent()
    }

我收到 id() 調用的錯誤,上面寫着

錯誤信息

  • 錯誤信息是什么意思?
  • 如何使用示例中給出的id()調用?

在編寫下面的代碼時,我在使用 jetpack compose 時也遇到了同樣的錯誤。

在我的情況下,上下文不清楚。

它給出了這個錯誤。

'fun item(key: Any? =..., content: LazyItemScope.() -> Unit): Unit' can't be called in this context by implicit receiver. Use the explicit one if necessary

它說在這種情況下不能調用 Unit 。 因此,我改變了上下文,一切都變得正確。

錯誤代碼:

LazyColumn {
       items(items = items) { word ->
           if (word != null) {
               WordColumnItem(word = word) {
                   onSelected(word)
               }
           }
           //Notice the context
           if(items.itemCount == 0) {
           item(
               content = { EmptyContent("No words") }
           )
       }
       }
   }

正確代碼:

LazyColumn {
        items(items = items) { word ->
            if (word != null) {
                WordColumnItem(word = word) {
                    onSelected(word)
                }
            }
        }
        //context changed.
        if(items.itemCount == 0) {
            item(
                content = { EmptyContent("No words") }
            )
        }
    }

雖然我不知道如何使用顯式接收器。(如有必要)

解決方案1)我認為錯誤很明顯。 2)您可以使用顯式接收器。

發生此錯誤是因為方法id(String)是在外部 scope 中定義的,並且為了防止您意外使用錯誤的方法,Kotlin 會給您一個編譯器錯誤。

為了使用顯式接收器,您應該執行以下操作, this scope 保存在變量中,然后在script scope 中調用它。

steps {
    val stepsThis = this
    script {
        name = "Style check"
        stepsThis.id("StyleCheck")
        enabled = false
        scriptContent = """
            #!/bin/bash

            make docker run="make ci lint"
        """.trimIndent()
    }
}

但是,這可能與您想要的效果不同,您應該確保沒有其他要使用的id 也許您想使用名為id的屬性而不是方法?

暫無
暫無

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

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