22

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

Jire
  • 9,680
  • 14
  • 52
  • 87
  • 3
    They're separate languages. Why would you expect a feature in one to automatically work in another? – yshavit Sep 16 '15 at 01:41
  • 1
    I thought that they added proper method references a few months ago. It's a necessary feature that saves boilerplate and that's what Kotlin is about. – Jire Sep 16 '15 at 01:42
  • 2
    They may have, I don't really know Kotlin. But I don't understand the connection to Java, since this question is fully about Kotlin. Have you checked the docs [on function references](http://kotlinlang.org/docs/reference/reflection.html#function-references)? – yshavit Sep 16 '15 at 01:46
  • 3
    See http://stackoverflow.com/questions/28022388/reference-to-method-of-a-particular-instance-in-kotlin – Kirill Rakhman Sep 16 '15 at 12:13
  • 1
    It's perhaps not as you like it but the workaround to just wrap it in a literal function like { writer.append(it) } works ok. – Lionel Port Sep 18 '15 at 04:58

3 Answers3

26

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.

Andrey Breslav
  • 24,795
  • 10
  • 66
  • 61
10

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.

Ilya
  • 21,871
  • 8
  • 73
  • 92
4

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.

rvazquezglez
  • 2,284
  • 28
  • 40