Java 8 Lambda function that throws exception?

后端 未结 26 1702
臣服心动
臣服心动 2020-11-22 03:14

I know how to create a reference to a method that has a String parameter and returns an int, it\'s:

Function         


        
26条回答
  •  隐瞒了意图╮
    2020-11-22 03:23

    What I'm doing is to allow the user to give the value he actually want in case of exception . So I've something looking like this

    public static  Function defaultIfThrows(FunctionThatThrows delegate, R defaultValue) {
        return x -> {
            try {
                return delegate.apply(x);
            } catch (Throwable throwable) {
                return defaultValue;
            }
        };
    }
    
    @FunctionalInterface
    public interface FunctionThatThrows {
        R apply(T t) throws Throwable;
    }
    

    And this can then be call like :

    defaultIfThrows(child -> child.getID(), null)
    

提交回复
热议问题