Effectively final effective?

Lawrence Kesteloot lk at teamten.com
Wed Feb 24 15:37:21 PST 2010


Let's come up with a semi-realistic example then. Something like:

    public #int(String,String) getClippedSortFunction(int clipLength) {
        return #(String a,String b) {
            String aClipped = a.substring(0, Math.min(clipLength, a.length()));
            String bClipped = b.substring(0, Math.min(clipLength, b.length()));

            return aClipped.compareTo(bClipped);
        };
    }

The "clipLength" is effectively final, so its value is copied into the
lambda and the sort happens fast. But then someone comes along later
and inserts this line at the top of the getClippedSortFunction()
method:

    clipLength = Math.max(1, clipLength);

The parameter is no longer effectively final, so the programmer gets a
warning (?), which he overrides with a click of the mouse in an IDE
(adding @Shared or whatever), and "clipLength" is now in the heap and
the sort slows down. Did I get that right?

The "final" modifier has bugged me in the past with anonymous inner
classes, but we really have no experience allowing large number of
programmers to write code without the restriction. For all we know it
would cause more confusion or more errors.

Lawrence


On Wed, Feb 24, 2010 at 3:16 PM, Alex Blewitt <alex.blewitt at gmail.com> wrote:
> On 24 Feb 2010, at 23:04, Mark Thornton wrote:
>
>> Neal Gafter wrote:
>>> It isn't just the visual noise that people find so bothersome.  The
>>> restriction itself is also bothersome, and harder to work around.
>> Yet would not many developers be surprised to discover that they
>> couldn't change an apparently ordinary local variable because it had
>> been captured by a lambda (or anonymous inner class) some lines previously.
>
> That's my concern too. The fact that it has to be final (save tricks like one-element arrays, atomic refs etc.) is part of documenting that restriction. Simply allowing it to be omitted doesn't change the fact that it is final.
>
> Would it be worthwhile asking the question of a larger audience to get their thoughts? Or have those at Sun/Oracle already done so at some point? As with 'most' other people, the set of who 'most' is is an interesting question, particularly since I wonder if the question had been asked in any other language than English :-)
>
> Alex
>
>


More information about the lambda-dev mailing list