Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Method reference not working?

Tags:

kotlin

It seems I'm unable to use a method reference of an object in Kotlin. This feature exists in Java.

For example in Java if I was looping through a string to append each character to a writer:

string.forEach(writer::append);

But in Kotlin using the same syntax does not work because:

enter image description here

like image 561
Jire Avatar asked Sep 16 '15 01:09

Jire


People also ask

Why method reference is better than lambda?

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

What does :: mean in Kotlin?

:: converts a Kotlin function into a lambda. this translates to MyClass(x, y) in Kotlin.

What is function reference in Kotlin?

A function reference is typically used to pass an expression or set of instructions from one part of your code to another. There are a few other ways to accomplish this in Kotlin.


1 Answers

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.

like image 173
Andrey Breslav Avatar answered Sep 19 '22 06:09

Andrey Breslav