Is it possible to assign the return of a lambda method to a variable in java?

Florian Castelain :

I have a function that builds a SQL query with a dynamic amount of where clauses.

The SQL query exeuction is stored into a ResultSet, I would like to declare this result set in the try with resource. However, this requires the declared elements to implements AutoCloseable, and the type String does not.

My idea was to use a lambda method, pass it as a parameter of executeQuery in order to use its return as the String parameter, like so:

try (Statement s = getStatement(); 
        String test = "test";
        ResultSet rs = s.executeQuery(() -> {
            String query = "build y query here";

            return query;
        });

        )

But this gives the following error on executeQuery:

The method executeQuery(String) in the type Statement is not applicable for the arguments (() -> {})

AS well as this on () ->:

he target type of this expression must be a functional interface

Is there a way to do what I want to achieve ?

Michael :

executeQuery takes a string. It does not take a Supplier<String> or anything similar. It requires the query to be supplied eagerly. The closest thing to what you're suggesting would be:

Supplier<String> supplier = () -> {
    String query = "build y query here";

    return query;
};
ResultSet rs = s.executeQuery(supplier.get());

Seeing as the supplier cannot be evaluated lazily, constrained by the signatures that Statement provides, there is absolutely no value in doing this. You may as well just extract that to a method.

ResultSet rs = s.executeQuery(buildQuery());

// ...

String buildQuery() {
    String query = "build y query here";

    return query;
}

Theoretically, they could add a Supplier<String> signature which would allow the Statement to defer construction of the query up until the last possible moment. This would likely be in the order of milliseconds later than if it has been constructed eagerly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20796&siteId=1