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())
}
}
But the kotlin parser complains about the type of c and I get for line 8 and 9:
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…