Joshua MN
Joshua MN

Reputation: 1516

Java 8 lambda scoping issue

    int x = 1;
    Consumer<Object> f = (i) -> {
        int x = 1; // invalid
    };

vs.

    Consumer<Object> f = (i) -> {
        int x = 1;
    };
    int x = 1; // valid

Imagine those two blocks inside a method. Why is the second block valid?

Upvotes: 2

Views: 168

Answers (2)

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

This is very similar to normal Java scopes:

int i;
{
    int i;      // invalid
}          

vs.

{
    int i;      // valid
}

int i;    

Upvotes: 5

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

In the first block you are "shadowing" the original x variable. You will not be able to access the first x anymore by creating a new x.

The second block is okay, because the second x is created on a moment when the first x does not longer exists (it is out of scope).

Basically: in the first case, you are trying to have two variables called x at the same time. In the second case, you are creating two x variables after each other: their lifetimes will not overlap.

Upvotes: 4

Related Questions