How to write Closure<String>


I am trying write some kotlin code. I got a val that is Closure and try to set the value.

val s:Closure <String> = {“test”}

I got compilation error:

Type mismatch: inferred type is () → String but Closure <String> was expected

how should it be written?


The compiler error is telling you. It needs to be:

val s: () -> String = {“test”}

Or, if you really have a type named Closure then maybe this will work:

val s: Closure<String> = Closure {“test”}

it is the same error. required Closure but it is () → String

I have tried to use gradle-kotlin-dsl library was able to use closureOf to construct Closure, but still struggle with building the function part so doCall does not throw exception

closureOf<String> ({
}) as Closure<String>

In kotlin closure is a lambda.

val a : () → Int = { 10 } should be enough. Or you can add receiver within a lambda

If this is about Gradle, then try:

closureOf<String> {

Sorry, I didn’t detail my issue well.

In Kotlin (.kt) file, there is variable typed as groovy.lang.Closure

I try to set the value for the variable in Kotlin (.kt) and that is when the issue comes. The closest is to use gradle-kotlin-dsl library and use
closureOf<String> ({
}) as Closure<String>

but it complains that receiver is null during runtime. so the closureOf function does not help in this case too. But I think it is doable to write a customized function to support this.

Can you show me the signature for closure of function?

I got kotlin source:
open class MyExtension {
var name: Closure? = null

and in my test in kotlin:

with (beerExtension) {
name = closureOf<String> ({
}) as Closure<String>

closureOf signature can be found at: