-2

Is it possible to invoke Function and Consumer where there are no input parameters? I tried using keywords void and Void but they are not doing the trick.

In the following code sample, if I uncomment methodRef2 and methodRef4, I get syntax errors.

import java.util.function.Function;
import java.util.function.Consumer;

public class StackOverflowExample {
    public static void main(String[] args) {
        Function<Integer, Integer> methodRef1 = StackOverflowExample::inIntegerOutInteger;
        methodRef1.apply(1000);

        //      Function<void, Integer> methodRef2 = StackOverflowExample::inVoidOutInteger;
        //      methodRef2.apply();

        Consumer<Integer> methodRef3 = StackOverflowExample::inIntegerOutVoid;
        methodRef3.accept(45);

        //      Consumer<void> methodRef4 = StackOverflowExample::inVoidOutVoid;
        //      methodRef4.accept();
    }

    protected static int inIntegerOutInteger(int i) {
        System.out.println("inIntegerOutInteger invoked with value " + i);
        return i;
    }


    protected static void inIntegerOutVoid(int i) {
        System.out.println("inIntegerOutVoid invoked with value " + i);
    }


    protected static int inVoidOutInteger() {
        int retVal = 1000;
        System.out.println("inVoidOutInteger invoked: returning value " + retVal);
        return retVal;
    }


    protected static void inVoidOutVoid() {
        System.out.println("inVoidOutVoid invoked");
    }

}
Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 3
    A function with no input is called a `Supplier`. A consumer with no input is called a `Runnable`. – marstran Oct 30 '19 at 07:28
  • In addition to @marstran take a look at functional interfaces more closely https://www.geeksforgeeks.org/functional-interfaces-java/ – Ivan Kaloyanov Oct 30 '19 at 07:31
  • Possible duplicate of [What is use of Functional Interface in Java 8?](https://stackoverflow.com/questions/36881826/what-is-use-of-functional-interface-in-java-8) – Ivan Kaloyanov Oct 30 '19 at 07:33
  • @IvanKaloyanov Not really a duplicate, at least of the link shared. – Naman Oct 30 '19 at 07:34
  • 1
    @Naman if he takes a few minutes to read about it I think he will be able to answer the question on his own. That's why I mark it – Ivan Kaloyanov Oct 30 '19 at 07:51

1 Answers1

2

Your methodRef2 should be of type Supplier:

Supplier<Integer> methodRef2 = StackOverflowExample::inVoidOutInteger;
methodRef2.get();

and methodRef4 should be of type Runnable:

Runnable methodRef4 = StackOverflowExample::inVoidOutVoid;
methodRef4.run();
Naman
  • 27,789
  • 26
  • 218
  • 353