javalambdajava-8method-reference

Difference between method reference Bound Receiver and Unbound Receiver


I am trying to use Java 8 method references in my code. There are four types of method references available.

  1. Static method reference.
  2. Instance method (bound receiver).
  3. Instance method (unbound receiver).
  4. Constructor reference.

With static method reference and constructor reference I have no problem, but instance method (bound receiver) and instance method (unbound receiver) really confused me. In bound receiver, we are using an object reference variable for calling a method like:

objectRef::Instance Method

In unbound receiver we are using class name for calling a method like:

ClassName::Instance Method.

I have the following question:

  1. What is the need for different types of method references for instance methods?
  2. What is the difference between bound and unbound receiver method references?
  3. Where should we use bound receiver and where should we use unbound receiver?

I also found the explanation of bound and unbound receiver from Java 8 language features books, but was still confused with the actual concept.


Solution

  • The idea of the unbound receiver such as String::length is you're referring to a method of an object that will be supplied as one of the lambda's parameters. For example, the lambda expression (String s) -> s.toUpperCase() can be rewritten as String::toUpperCase.

    But bounded refers to a situation when you're calling a method in a lambda to an external object that already exists. For example, the lambda expression () -> expensiveTransaction.getValue() can be rewritten as expensiveTransaction::getValue.

    Situations for three different ways of method reference

    Answer retrieved from Java 8 in Action book