Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

  1. Reference to an instance method of a particular object.
  2. Reference to an instance method of an arbitrary object of a particular type.

Both refer to references but what's significantly different? Is it that the type inference used to resolve them is different? Is it significant that (in their examples) one is a closure and the other is a lambda? Is it something to do with the number of arguments on a method?

like image 717
Toby Avatar asked Mar 19 '14 19:03

Toby


People also ask

What is method Refrence in Java 8?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

What is the benefit of using method reference in Java 8?

That's all about what is method reference is in Java 8 and how you can use it to write clean code in Java 8. The biggest benefit of the method reference or constructor reference is that they make the code even shorter by eliminating lambda expression, which makes the code more readable.

What is the use of method reference in Java?

There are several types of a method reference in Java that are allowed in Java 8. Reference to some static methods: The static methods in a code can be referred to from a class. Reference to some instance method of particular objects: Reference to some instance method of an arbitrary object of any particular type.


2 Answers

  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).

like image 67
Louis Wasserman Avatar answered Sep 28 '22 10:09

Louis Wasserman


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.

like image 24
skiwi Avatar answered Sep 28 '22 09:09

skiwi