user2880771 user2880771 - 2 months ago 6
Java Question

Java Eclipse Lambda function error

The following code produces an error for me in Eclipse Luna and prevents from running.

jdbcTemplate.query( query, r -> {
Folder folder = new Folder();
folder.setId(r.getLong("id"));
folder.setFolderName(r.getString("folder_name"));
folder.setFullPath(r.getString("full_path"));
folders.add(folder);
}, folderId);

return folders;
}


The error occurs at jdbcTemplate.query

The method query(String, ResultSetExtractor<Object>, Object[]) is ambiguous for the type JdbcTemplate


Error does not occur when I package file as jar and run.

Thanks for any guidance or suggestions.

ctg ctg
Answer

There are three query methods in JdbcTemplate, as follows:

query(String, ResultSetExtractor<T>);
query(String, RowCallbackHandler);
query(String, RowMapper<T>);

In all three, the second argument can be implemented as a lambda, and the two that have a generic <T> parameter will return something. Eclipse is complaining that it can't tell the difference between the first and the third method you are referring to, so you need to specify the type of the functional interface that the lambda is replacing. Additionally, as Jack Ammo says, you need to return an object from the lambda to satisfy the interface. Don't add the returned object to your list of folders inside the lambda, either. So, you'd be looking at something like this:

Folder folder = jdbcTemplate.query( query, (ResultSetExtractor<Folder>) r -> {
    Folder folder = new Folder();
    folder.setId(r.getLong("id"));
    folder.setFolderName(r.getString("folder_name"));
    folder.setFullPath(r.getString("full_path"));
    return folder;
}, folderId);

folders.add(folder);

return folders;