Java 8 Lambda function that throws exception?

后端 未结 26 1727
臣服心动
臣服心动 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:21

    If you don't mind to use a 3rd party lib (Vavr) you could write

    CheckedFunction1 f = this::myMethod;
    

    It also has the so-called Try monad which handles errors:

    Try(() -> f.apply("test")) // results in a Success(Integer) or Failure(Throwable)
            .map(i -> ...) // only executed on Success
            ...
    

    Please read more here.

    Disclaimer: I'm the creator of Vavr.

提交回复
热议问题