在此上下文中,隐式接收者无法调用单元

Sen*_*ran 14 kotlin

我正在关注这个 Kotlin 示例(https://www.jetbrains.com/help/teamcity/kotlin-dsl.html#Editing+Kotlin+DSL)并尝试为我的 CI 编写一个 kotlin 脚本。

这是我的代码片段

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

            make docker run="make ci lint"
        """.trimIndent()
    }
Run Code Online (Sandbox Code Playgroud)

我收到 id() 调用错误,其中显示

错误信息

  • 错误信息是什么意思?
  • 如何使用id()示例中给出的调用?

Sim*_*erg 6

发生此错误的原因是该方法id(String)是在外部作用域中定义的,为了防止您意外使用错误的方法,Kotlin 会向您提供编译器错误。

对于你的情况,你应该确保没有其他id你想使用的。也许您想使用指定的属性id而不是方法?


请注意,以下两个选项都可能无法达到您想要的效果。API 如此编写可能是有原因的,因为不允许您从内部作用域内部调用外部接收器的方法。

为了使用显式接收器,您可以使用this@methodName来调用它。在这种情况下,this@steps

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

            make docker run="make ci lint"
        """.trimIndent()
    }
}
Run Code Online (Sandbox Code Playgroud)

要准确了解发生的情况以及使用显式接收器的另一种方法,您还可以执行如下操作,将作用域保存this在变量中,然后在script作用域内调用它。

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

            make docker run="make ci lint"
        """.trimIndent()
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

当我编写下面的代码时,我在使用 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

它说在这种情况下不能调用单位。因此我改变了上下文,一切都变得正确了。

错误代码:

LazyColumn {
       items(items = items) { word ->
           if (word != null) {
               WordColumnItem(word = word) {
                   onSelected(word)
               }
           }
           // Notice the context: within `items()` call
           if (items.itemCount == 0) {
               item(
                   content = { EmptyContent("No words") }
               )
           }
       }
   }
Run Code Online (Sandbox Code Playgroud)

正确代码:

LazyColumn {
        items(items = items) { word ->
            if (word != null) {
                WordColumnItem(word = word) {
                    onSelected(word)
                }
            }
        }
        // Context changed: outside `items()` call
        if (items.itemCount == 0) {
            item(
                content = { EmptyContent("No words") }
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

虽然我不知道如何使用显式接收器(如果需要)。

解决方案

  1. 我认为错误是显而易见的。
  2. 您可以使用显式接收器。

  • 您没有解释什么是“显式接收者”。那么**如何**可以使用它呢? (5认同)