When lambdas become objects

Michael Hixson michael.hixson at gmail.com
Tue Nov 27 20:34:50 PST 2012


Thank you, that clears things up a lot.

>> Does every invocation of nonNull() return the same Predicate instance?
>
>
> Implementations are permitted to do so, and ours (mostly) does.  But this is not guaranteed and you should not assume that it does.

When you say I shouldn't assume that it does, you mean that I
shouldn't rely on that behavior for my program's correctness, right?
I would like to be able to assume it performs this way because the
code is cleaner than the  strategy used in the real
j.u.f.Predicates.nonNull -- returning a casted static
Predicate<Object>.

>> Does every invocation of isFunActivity() return a separate Predicate
>> instance?  Or, would a given FunDetector instance always return the same
>> Predicate instance?
>
>
> Because isFun is an instance method, you have to capture the receiver variable 'this', so each capture is likely to result in a new object. (Note you could have written this both more compactly and more explicitly as "return this::isFun".)

Are there plans to eventually do some sort of instance-level caching &
reuse of these lambdas, when the lambdas only capture 'this', either
later in the JDK8 development cycle or else in a future version of
Java?

I've found that kind of lambda to be extremely common in the code I
ported.  I realize I could convert the inline lambdas to member
variables to avoid the extra objects if I wanted to.  I probably
wouldn't bother (because the inline versions tend to be more
readable), but if you told me a near-future version of Java would have
this 'this'-capturing-lambda-cache optimization then I wouldn't think
about the issue at all.

>> Does every invocation of weirdSort(list, flag) cause the creation of
>> exactly two Comparators?  Or does every comparison made by the outer
>> Comparator lambda cause the creation of an additional Comparator (for the
>> inner lambda)?
>
>
> The latter.  The inner lambda is captured when the outer lambda is executed, and the inner lambda captures the 'flag' variable.
>
> You could rewrite it to not do so, by pulling the inner lambda out to the top level of weirdSort, and capturing that.
>

Right, makes sense.

-Michael


More information about the lambda-dev mailing list