Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - how do I declare a method reference to an unbound non-static method that returns void

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.

like image 913
John Calcote Avatar asked Oct 07 '17 01:10

John Calcote


People also ask

How do you call a method without static?

To call a non-static variable from a static method, an instance of the class has to be created first. In this example, the integer a is not static. So to access it from the static method main, an instance of the class Calc has to be created.

How can we call non static methods from static methods in Java explain with code?

To call a non-static method from main in Java, you first need to create an instance of the class, post which we can call using objectName. methodName().

How do you call a method in Java without static?

If we are calling a non static method then we need to use object so that it will call corresponding object non static method. Non static methods will be executed or called by using object so whenever we want to call a non static method from static method we need to create an instance and call that method.

What is an unbound reference?

In unbound references, the receiving object is specified when the function object is applied, via an additional parameter before the method's declared parameters. Unbound references are often used as mapping and filter functions in stream pipelines.


1 Answers

BiFunction represents a function that accepts two arguments and 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);
like image 134
Ousmane D. Avatar answered Oct 06 '22 11:10

Ousmane D.