Kotlin: Method reference not working?

Starting from Kotlin 1.1 writer::append is a perfectly valid bound callable reference.

However, you still cannot write string.forEach(writer::append) because Writer#append method returns a Writer instance and forEach expects a function that returns Unit.


For now, Kotlin only supports references to top-level and local functions and members of classes, not individual instances. See the docs here.

So, you can say Writer::append and get a function Writer.(Char) -> Writer, but taking a writer instance and saying writer::append to get a function (Char) -> Writer is not supported at the moment.


I am using Kotlin 1.3 and while referencing a Java method I got a very similar error. As mentioned in this comment, making a lambda and passing it to the forEach method is a good option.

key.forEach { writter.append(it) }

Being it the implicit name of a single parameter.

Tags:

Kotlin