Reputation: 10290
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:
Upvotes: 23
Views: 17850
Reputation: 2454
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.
Upvotes: 4
Reputation: 23115
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
.
Upvotes: 10
Reputation: 25767
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.
Upvotes: 26