Passing a named function as a parameter to a higher order function


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.


In order to get an instance of functional type from a named function, you need to get a callable reference from it. It’s obtained with the :: operator:

fun baz() { bar(::foo) }


Thanks, don’t know how I missed that in the reference.