Here's a simple class that illustrates my problem:
package com.example;
import java.util.function.*;
public class App {
public static void main(String[] args) {
App a1 = new App();
BiFunction<App, Long, Long> f1 = App::m1;
BiFunction<App, Long, Void> f2 = App::m2;
f1.apply(a1, 6L);
f2.apply(a1, 6L);
}
private long m1(long x) {
return x;
}
private void m2(long x) {
}
}
f1
, referring to App::m1
, and being bound to a1
in f1
's call to apply
, works perfectly fine - the compiler is happy and the call can be made through f1.apply just fine.
f2
, referring to App::m2
, doesn't work.
I'd like to be able to define a method reference to an unbound non-static method with no return type, but I can't seem to make it work.
BiFunction
represents a function that accepts two arguments a nd produces a result .
I'd like to be able to define a method reference to an unbound non-static method with no return type
use a BiConsumer
instead which represents an operation that accepts two input arguments and returns no result .
BiConsumer<App, Long> f2 = App::m2;
then change this:
f2.apply(a1, 6L);
to this:
f2.accept(a1, 6L);
The method reference is App::m2, just like you have, but it's not assignable to a BiFunction, because it doesn't return a value, even a Void value (which has to be null
). You'd have to do:
f2 = (a,b) -> { m2(a,b); return null; }
if you want a BiFunction. Alternatively, you could use a BiConsumer as mentioned in other answers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.