Pass class method as function reference


#1

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?


#2

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


#3

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.


#4

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?


#5

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


#6

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:


#7

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


#8

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.


#9

For sure it will work on java 6


#10

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