Multiline lambda
Asked Answered
L

2

8

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?

Lebkuchen answered 11/2, 2020 at 9:45 Comment(2)
Post the code you tried and didn't work.Sec
Does this answer your question? Multiline lambda comparatorSunshade
D
9

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");
        }) 
    );
Dorene answered 11/2, 2020 at 9:47 Comment(0)
C
6

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);
Chellman answered 11/2, 2020 at 22:7 Comment(2)
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.Downer
Just for background reading, Why the perfect lambda expression is just one line explains nicely why you could consider multiple statements in a lambda a code smell.Harberd

© 2022 - 2024 — McMap. All rights reserved.