Java 8 lambda Void argument

前端 未结 9 627
臣服心动
臣服心动 2020-12-12 08:30

Let\'s say I have the following functional interface in Java 8:

interface Action {
   U execute(T t);
}

And for some cases I ne

相关标签:
9条回答
  • 2020-12-12 09:25

    Just for reference which functional interface can be used for method reference in cases method throws and/or returns a value.

    void notReturnsNotThrows() {};
    void notReturnsThrows() throws Exception {}
    String returnsNotThrows() { return ""; }
    String returnsThrows() throws Exception { return ""; }
    
    {
        Runnable r1 = this::notReturnsNotThrows; //ok
        Runnable r2 = this::notReturnsThrows; //error
        Runnable r3 = this::returnsNotThrows; //ok
        Runnable r4 = this::returnsThrows; //error
    
        Callable c1 = this::notReturnsNotThrows; //error
        Callable c2 = this::notReturnsThrows; //error
        Callable c3 = this::returnsNotThrows; //ok
        Callable c4 = this::returnsThrows; //ok
    
    }
    
    
    interface VoidCallableExtendsCallable extends Callable<Void> {
        @Override
        Void call() throws Exception;
    }
    
    interface VoidCallable {
        void call() throws Exception;
    }
    
    {
        VoidCallableExtendsCallable vcec1 = this::notReturnsNotThrows; //error
        VoidCallableExtendsCallable vcec2 = this::notReturnsThrows; //error
        VoidCallableExtendsCallable vcec3 = this::returnsNotThrows; //error
        VoidCallableExtendsCallable vcec4 = this::returnsThrows; //error
    
        VoidCallable vc1 = this::notReturnsNotThrows; //ok
        VoidCallable vc2 = this::notReturnsThrows; //ok
        VoidCallable vc3 = this::returnsNotThrows; //ok
        VoidCallable vc4 = this::returnsThrows; //ok
    }
    
    0 讨论(0)
  • 2020-12-12 09:28

    I think this table is short and usefull:

    Supplier       ()    -> x
    Consumer       x     -> ()
    Callable       ()    -> x throws ex
    Runnable       ()    -> ()
    Function       x     -> y
    BiFunction     x,y   -> z
    Predicate      x     -> boolean
    UnaryOperator  x1    -> x2
    BinaryOperator x1,x2 -> x3
    

    As said on the other answers, the appropriate option for this problem is a Runnable

    0 讨论(0)
  • 2020-12-12 09:29

    Use Supplier if it takes nothing, but returns something.

    Use Consumer if it takes something, but returns nothing.

    Use Callable if it returns a result and might throw (most akin to Thunk in general CS terms).

    Use Runnable if it does neither and cannot throw.

    0 讨论(0)
提交回复
热议问题