Java:将void与Function <T,R>和Consumer <T>一起使用

时间:2019-10-30 07:25:28

标签: java generics functional-programming

是否可以在没有输入参数的地方调用Function和Consumer?我尝试使用关键字void和Void,但它们没有成功。

在下面的代码示例中,如果取消注释methodRef2和methodRef4,则会出现语法错误。

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");
    }

}

1 个答案:

答案 0 :(得分:2)

您的methodRef2的类型应为Supplier

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

methodRef4的类型应为Runnable

Runnable methodRef4 = StackOverflowExample::inVoidOutVoid;
methodRef4.run();