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

Viewed 3107

I am following this Kotlin example (https://www.jetbrains.com/help/teamcity/kotlin-dsl.html#Editing+Kotlin+DSL) and trying to write a kotlin script for my CI.

This is my code snippet

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

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

I get an Error for the id() call which says

Error message

  • What does the error message mean?
  • How can I use id() call as given in the example?
2 Answers

I also got the same error when working with jetpack compose when I was writing the code below.

In my case the context was not clear.

It was giving this error.

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

It says Unit can't be called in this context. Therefore I changed the context and everything got right.

Error code:

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

Correct code:

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

Although I don't know how to use the explicit receiver.(if necessary)

Solution 1) I think error is clear. 2) You can use explicit receiver.

This error happens because the method id(String) is defined in an outer scope, and to prevent you from accidentally using the wrong method, Kotlin gives you a compiler error.

In order to use an explicit receiver, you should do something like the below, where you save the this scope in a variable and then call it inside the 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()
    }
}

However, this may not have the same effect as you want and you should make sure that there's no other id that you want to use. Perhaps you wanted to use the property named id instead of the method?

Related