Return Lambda from Method in Java 8?
Asked Answered
T

5

45

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:

Function<Integer, String> getMyFunction() {
  return new Function<Integer, String>() {
    @Override public String apply(Integer integer) {
      return "Hello, world!"
    }
  } 
}

Is there a way to write that more succinctly in Java 8? I was hoping this would work but it does not:

Function<Integer, String> getMyFunction() {
  return (it) -> { return "Hello, world: " + it } 
}
Triserial answered 6/11, 2014 at 4:51 Comment(0)
W
52

Get rid of your return statement inside of your function definition:

Function<Integer, String> getMyFunction() {
    return (it) -> "Hello, world: " + it;
}
Webfooted answered 6/11, 2014 at 4:56 Comment(0)
B
25

You are missing semi colons:

return (it) -> { return "Hello, world: " + it; };

Although as noted it can be shortened to:

return it -> "Hello, world: " + it;
Boogeyman answered 6/11, 2014 at 6:22 Comment(0)
F
7

I would like to point out that it might be more appropriate to use the built-in IntFunction in this case:

IntFunction<String> getMyFunction() {
    return it -> "Hello, world: " + it;
}

IntFunction is a part of the standard API for functional interfaces which defines a range of good to have interfaces, mostly related to Java primitives.

Farant answered 14/9, 2016 at 6:31 Comment(0)
P
5

You could write it simply like that:

Function<Integer, String> function = n -> "Hello, world " + n;
Porscheporsena answered 7/11, 2014 at 10:22 Comment(0)
D
4

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<YourClass> 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)

Decidua answered 21/4, 2016 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.