Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot directly use `get` on a `Supplier` lambda expression

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading