What's the difference between instance method reference types in Java 8?

前端 未结 3 1389
感情败类
感情败类 2020-11-27 06:16

So Java 8 introduces method references and the docs describe the four types.

My question is what\'s the difference between the two instance types?

相关标签:
3条回答
  • 2020-11-27 06:17

    I wrote up the conclusion I came to here, the following is a summary.

    Oracle describe the four kinds of method reference as follows.

    What they should have written is:

    I found their description of the first two confusing ("reference to a static method" and "reference to an instance method of a particular objects"), I think its really the difference between a class static and an object.

    I prefer to think of the first as an instance method of a specific object known ahead of time and the second as an instance method of an arbitrary object that will be supplied later. Interestingly, this means the first is a closure and the second is a lambda. One is bound and the other unbound.

    The distinction between a method reference that closes over something (a closure) and one that doesn’t (a lambda) may be a bit academic but at least it’s a more formal definition than Oracle’s unhelpful description. If you’re interested in the difference between a closure and a lambda, check out this post.

    Summary

    The difference between the two types of instance method reference is interesting but basically academic. Sometimes, you’ll need to pass something in, other times, the usage of the lambda will supply it for you. My gripe is with Oracle’s documentation. They make a big deal out of the distinction but fail to describe it in an easily understandable way. It’s the canonical reference material but it’s just plain confusing.

    There's one or two more subtleties to it that I wrote up.

    0 讨论(0)
  • 2020-11-27 06:29
    1. myString::charAt would take an int and return a char, and might be used for any lambda that works that way. It translates, essentially, to index -> myString.charAt(index).

    2. String::length would take a String and return an int. It translates, essentially, to string -> string.length().

    3. String::charAt would translate to (string, index) -> string.charAt(index).

    0 讨论(0)
  • 2020-11-27 06:43

    With this they mean that you have the following:

    1) Can be for example this::someFunction;, this will return the someFunction reference of the current object.

    2) Can be for example String::toUpperCase, this will return the toUpperCase method of String in general.

    I am not sure if there is an actual difference in behaviour, I think it is just like you can also call static methods on instance variables.

    0 讨论(0)
提交回复
热议问题