Return Lambda from Method in Java 8?

后端 未结 5 1464
轮回少年
轮回少年 2021-01-31 03:01

I have just begun to use Java 8 and I am wondering if there is a way to write a method that returns a Function?

Right now I have method like below:

5条回答
  •  清酒与你
    2021-01-31 03:21

    So, the answer for 99% of the cases has been given by @assylias

    You are missing semi colons:

    return (it) -> { return "Hello, world: " + it; }; Although as noted it can be shortened to:

    return it -> "Hello, world: " + it;

    Yet, I think that it's worth it to add that, if you want to assign your lambda to a variable (to use later). You can do so by typing:

    Callable findIt = () -> returnInstanceOfYourClass();
    

    And then you can easily use it, one example of such a use:

    if(dontNeedzToWrap()) {
                    return findIt.call();
      }
    return Wrapp.withTransaction(() -> findIt.call());
    

    Given, things can be even made simpler if the Wrapp.withTransaction() method accepts the same kind of Callable's as parameters. (I use this for JPA atm)

提交回复
热议问题