Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to specify a function type in the parameters of a Kotlin lambda?

So I was trying to register some functions in a map, the code can be resumed like this:

private val things = mutableMapOf<String, Any>()

fun put(name: String, value: Any) {
    things[name] = value
}

fun main() {
    put("foo") { a: String, b: (() -> String) ->
        println(a + b())
    }
}

(Code on Kotlin Playground)

But the kotlin parser complains about the type of c and I get for line 8 and 9:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unresolved reference: a
Unexpected tokens (use ';' to separate expressions on the same line)
Unresolved reference: a
Unresolved reference: b

It seems like a bug but I’m not sure.

Of course, this could be worked around my specifying the type of value in register to (String, () -> String) -> Unit, but this is the API and I have no access to it.

This could also be worked around by using a Function0<String>, but why wouldn’t it work with the more "kotlin" syntax ?

>Solution :

Removing the parentheses around the function type worked for me:

put("foo") { a: String, b: () -> String ->
    println(a + b())
}

I do agree this is weird. You can put parentheses around String, but not () -> String. This also works with anonymous function literals:

put("foo", fun(a: String, b: (() -> String)) {
    
})

The syntax in the language spec does say that type can be a parenthesizedType:

type:
[typeModifiers] (functionType | parenthesizedType | nullableType | typeReference | definitelyNonNullableType)

Perhaps there is some quirk in the parser that causes the parsing the fail…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading