Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Get Operator-Function-Object with method reference

I wondered if there is a possibility in Java 8, to get the method references of the standard operators (+, -, <, >, ...).

I want to get it like Foo::+ where Foo is some defined place where i can get it. Since Java doesn't allow special characters in method names I don't think it's possible, is it?

If the way above doesn't exist: Is there some place where the standard operators are defined like Foo::plus?

I know there is the possiblity of defining it as lambda ((x, y) -> x + y), but in my opinion it could be more expressive in some cases with a method reference to the operator like it's possible in Haskell.

like image 976
F. Böller Avatar asked Jul 17 '14 11:07

F. Böller


2 Answers

I believe you are looking for int Integer.sum(int, int) and similar methods, which are indeed provided by the API.

There are many methods from your list missing, but it's common for the JDK not to provide the last inch of convenience because its size is enormous even without those.

If that's any consolation, each of my projects has a Util class where I dump tidbits such as these.

like image 196
Marko Topolnik Avatar answered Oct 21 '22 17:10

Marko Topolnik


A clean way would be an Operators helper class that contains methods for all operators. Then you could use these methods as references. Of course, a standard library class would be nicer than an own helper class, but at least you can decide the name of that helper class, so you can choose a name that is most expressive to you.

like image 30
gexicide Avatar answered Oct 21 '22 16:10

gexicide