Pass class method as function reference

I have the following code

fun visit<T>(provider : () -> T?, process : (value : T) -> Unit) : Unit {   while (true) {   val value = provider()   if (value == null)            break

  &nbsp;&nbsp;process(value)

  }
}

fun processFile(file : File, filter : (line : String) -> Boolean, processor : (line : String) -> Unit) : Unit {
  val reader = BufferedReader(FileReader(file))
  try {
  val provider = { () : String? ->
           reader.readLine()
  }

  &nbsp;&nbsp;visit(provider) { (line : String) -&gt;

           if (filter(line)) {
           processor(line)
           }
  }
  } finally {
  reader.close()
  }
}

This code works as expected, but…

Is there way to pass reader.readLine to visit function directly?

I hope you can say {reader.readLine()} instead of {() : String? -> reader.readLine()}. Otherwise, it's a bug.

As of passing a member as a function value, wee this request: http://youtrack.jetbrains.com/issue/KT-1183

Oh, thank you. I tried { return reader.readLine() } instead of just { reader.readLine() }. It works. But I dreamed about something like  visit(reader.readLine) {}  so ticket you refered to is also correct.

I just voted for this feature, thanks for the link, Andrey. I think supporting function literals is important.

It’s not clear to me from the request that this feature is on the road map or not, can you clarify?

It is on the roadmap, but not a high-priority one.

Why “not a high-priority one”? C# does that, Java 8 does that, Obj-C does that, C+ does that, even AS3 does that :slight_smile: It’s a really common feature, widely used e.g. for event handling (like C# style events) and after going through feature requests for Kotlin I can say it didn’t find any other with more votes (https://youtrack.jetbrains.com/issue/KT-6947), so it’s clearly something worth being added.

edit: Just noticed this thread is over 4 years old, so hopefully priorities have changed :slight_smile:

Bound method references are on the roadmap for Kotlin 1.1, as the linked issue shows.

Yes, I just got confused by the previous reply about it not being a high-priority thing (I read it as a reply from 12 March, not March 2012 :slight_smile:

But since I got your attention by making a fool out of myself, I’ve got another question to ask: Will this feature require Java 8 or not? I read somewhere your aim is to make Kotlin code 100% Java compatible, so Java programmers could call Kotling stuff without any problems and I’m not sure if this is doable on Java 6 JVM.

For sure it will work on java 6

Ah, just noticed that this is my thread I have opened before joined the team :slight_smile:

3 Likes