Reputation: 63
I'm trying to declare a HashMap
which will take a string and return a Callable
.
I have:
Map<String, Callable<String>> commands = new HashMap<>();
commands.put("get", (String item) -> get(item));
where get is a function which returns void.
But I'm getting
"Bad return type in Lambda expression: Void cannot be converted into a string."
Why is it expecting the function to return a string? I want to pass the lambda a String
and get void
back.
Upvotes: 6
Views: 10271
Reputation: 48404
The correct syntax for a putting a lambda representation of a Callable<String>
as value into your map would be:
Map<String, Callable<String>> commands = new HashMap<>();
commands.put("get", () -> "some value");
That is because the functional interface Callable<T>
has a single method returning a T
value.
Upvotes: 0
Reputation: 393801
A Callable<String>
has a method that returns a String
(V call() throws Exception
), so you can't use a lambda with void return type. You can use a Consumer<String>
instead.
Map<String, Consumer<String>> commands = new HashMap<>();
commands.put("get", (String item) -> get(item));
Upvotes: 8