Home > database >  Cannot directly use `get` on a `Supplier` lambda expression
Cannot directly use `get` on a `Supplier` lambda expression

Time:11-13

I'll make it simple. Why does the following code compile:

final int[] arr = { 1, 2, 3, 4 };
final Supplier<Integer> summer = () ->
{
    int temp = 0;
    for (int i : arr) { temp  = i; }
    return temp;
};
final int sum = summer.get();

But not this one?

final int[] arr = { 1, 2, 3, 4 };
final int sum = (() ->
{
    int temp = 0;
    for (int i : arr) { temp  = i; }
    return temp;
}).get();

Error message:

SupplierTest.java:8: error: lambda expression not expected here
                final int sum = (() ->
                                 ^
1 error
error: compilation failed

CodePudding user response:

You need a target type to identify what class the lambda is implementing. Otherwise there's no way to know whether you're declaring a Supplier or, say, a Callable. But if you want to avoid the variable, you can use a cast instead:

final int[] arr = { 1, 2, 3, 4 };
final int sum = ((IntSupplier)() ->
{
    int temp = 0;
    for (int i : arr) { temp  = i; }
    return temp;
}).getAsInt();

That said, I hope this is a theoretical exercise. There's almost no reason to use this in real code.

  • Related