When lambdas become objects
Michael Hixson
michael.hixson at gmail.com
Tue Nov 27 17:48:44 PST 2012
Hello,
I have a few questions about when lambdas are converted into objects, and
how often.
1. Non-capturing, but inferring generic type:
public static <T> Predicate<T> nonNull() {
return t -> t != null;
}
Does every invocation of nonNull() return the same Predicate instance?
2. Capturing methods or member variables from the enclosing class:
class FunDetector {
private boolean isFun(Activity activity) { ... }
public Predicate<Activity> isFunAcitivity() {
return activity -> isFun(activity);
}
}
Does every invocation of isFunActivity() return a separate Predicate
instance? Or, would a given FunDetector instance always return the same
Predicate instance?
3. Lambda within a lambda, both capturing a variable from the calling
method:
(This example uses the ComparisonChain class from Guava:
http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/index.html?com/google/common/collect/ComparisonChain.html)
void weirdSort(List<String> list, boolean flag) {
list.sort((a, b) -> ComparisonChain.start()
.compare(
a.charAt(0),
b.charAt(0),
(x, y) -> Character.compare(
flag ? Character.toLowerCase(x) : Character.toTitleCase(x),
flag ? Character.toLowerCase(y) : Character.toTitleCase(y)))
.compare(
flag ? a.length() : a.hashCode(),
flag ? b.length() : b.hashCode())
.result());
}
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)?
-Michael
More information about the lambda-dev
mailing list