Is there a way to pass a named function (ie one defined with fun
) as a parameter to a higher order function? When I try to do this the compiler seems to treat the reference to the named function as an invocation with missing parameters, for example:
fun foo() { System.out.println("Hello world") }
fun bar(fn: ()->Unit) { fn() }
fun baz() { bar(foo) }
causes this error:
Function invocation ‘foo()’ expected
Type mismatch: inferred type is Unit but () → Unit was expected
with the error highlight shown under the final use of foo
.
I can work around this by rewriting foo
as a val
initialised with a lambda, but it seems strange I can’t do it the first way. Yet I can’t find anything in the Kotlin reference etc describing some sort of syntax for it.