7

I have this code, which works:

  new JdbcTemplate(new SingleConnectionDataSource(c, true))
        .query("select id, name from PLAYERS", (rs, rowNum) ->
            new Player(rs.getString("id"), rs.getString("name")) // oneline
        );

However I now need to add multiple statements in the new Player() part. I tried enclosing them in brackets, but it doesn't seem to work. What's the correct syntax?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
BobJI
  • 163
  • 1
  • 9
  • 3
    Post the code you tried and didn't work. – Guy Feb 11 '20 at 09:46
  • 1
    Does this answer your question? [Multiline lambda comparator](https://stackoverflow.com/questions/27150608/multiline-lambda-comparator) – ggorlen Sep 24 '20 at 18:34

2 Answers2

7

I'm assuming the method of the functional interface implemented by this lambda expression has a return value, so when using brackets, it should include a return statement, just like any method with non-void return type.

new JdbcTemplate(new SingleConnectionDataSource(c, true))
    .query("select id, name from PLAYERS", (rs, rowNum) ->
        {
            return new Player(rs.getString("id"), rs.getString("name");
        }) 
    );
Eran
  • 387,369
  • 54
  • 702
  • 768
4

Don't do that. Having multiple statements in a lambda in most cases is a code smell. Rather create a method with two parameters:

private Player toPlayer(ResultSet rs, int rowNum) {
    // multiple setters here
    return player;
}

And then pass the method reference (which in fact will behave like a BiFunction) instead of lambda:

new JdbcTemplate(new SingleConnectionDataSource(c, true))
    .query("select id, name from PLAYERS", this::toPlayer);

One may want to create a static utility method instead of a dynamic one. The logic is the same as above:

public class MappingUtil {
    // ...
    public static Player toPlayer(ResultSet rs, int rowNum) {
        // multiple setters here
        return player;
    }
}

And then:

new JdbcTemplate(new SingleConnectionDataSource(c, true))
    .query("select id, name from PLAYERS", MappingUtil::toPlayer);
ETO
  • 6,970
  • 1
  • 20
  • 37
  • 6
    My best guess is that some people judged that your answer was too opinionated; it would be better to explain why you think multi-line lambdas are bad style or otherwise problematic, to support it rather than asserting your opinion. That said, I think your answer is useful, so I upvoted. – kaya3 Feb 14 '20 at 18:47
  • Just for background reading, [Why the perfect lambda expression is just one line](https://developer.ibm.com/languages/java/articles/j-java8idioms6/) explains nicely why you could consider multiple statements in a lambda a code smell. – Jacob van Lingen Jul 23 '21 at 07:10