23

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

5
  • 3
    They're separate languages. Why would you expect a feature in one to automatically work in another? Commented Sep 16, 2015 at 1: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. Commented Sep 16, 2015 at 1: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? Commented Sep 16, 2015 at 1:46
  • 3
    See stackoverflow.com/questions/28022388/… Commented Sep 16, 2015 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. Commented Sep 18, 2015 at 4:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Are there plans to add the feature in a future Kotlin version?
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.