Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Java 8 method references different from 'real' function pointers?

Someone told me tbat Java 8 method references aren't as powerful as 'true' function pointers.

How is it so? How are method references different from function pointers?

like image 875
Aviv Cohn Avatar asked Feb 13 '26 08:02

Aviv Cohn


1 Answers

What is currying?

Currying is the ability to construct a new method reference from an existing method and an argument. e.g.

// this is curried and implied in this method.
BiFunction<String, Integer> m = this::methodTwo;

// create a new curried method.
Function<String> m10 = t -> m.apply(t, 10);

A real example is a consumer

// curry this method so that when called it prints to System.out
Consumer<String> out = System.out::println;

Java 8 method references aren't as powerful as 'true' function pointers.

Java 8 method references are actually a reference to an object which encapsulates a virtual method. This works very well up to a point, but some basic things you might expect you can't do. e.g. equals(), toString(), expression examination won't do what you might expect.

How are method references different from function pointers?

A function pointer is purely a reference to a function. A method reference in Java includes currying information e.g. this a method which has X, Y, Z as know arguments.

does Java 8 support true closures?

Java tends to be minimalist in terms of features, but you can take it as given than no feature in Java is "pure". It has too much backward compatibility issues to deal with that even if there was the will to be pure, it couldn't be.

do we still need to declare a variable final before being able to use it in a lambda?

No, "effectively final" is good enough. i.e. if you could have made it final, it is ok.

like image 199
Peter Lawrey Avatar answered Feb 15 '26 23:02

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!