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?
No, you can't write multiline lambda in Python because the lambda functions can have only one expression. The creator of the Python programming language – Guido van Rossum, answered this question in one of his blogs. where he said that it's theoretically possible, but the solution is not a Pythonic way to do that.
No, you cannot write multiple lines lambda in Python. The lambda functions can have only one expression. One logical answer to this question is that if you want to write multiline functions, then you should use regular functions in Python; why do you go for multiline lambdas.
In Java 8, it is also possible for the body of a lambda expression to be a complex expression or statement, which means a lambda expression consisting of more than one line. In that case, the semicolons are necessary. If the lambda expression returns a result then the return keyword is also required.
In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.
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");
})
);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With