Expected distribution of lambda sizes (Re: Syntax poll, take 2)
Stephen Colebourne
scolebourne at joda.org
Tue Jun 14 03:18:56 PDT 2011
On 13 June 2011 18:34, Brian Goetz <brian.goetz at oracle.com> wrote:
> So I am not sure I agree with your assumption that lambdas will mostly
> be multi-statement.
I would love to agree that most lambdas will be short and that the
APIs will push in that direction. I can understand how comparisons
with other languages (Groovy, Scala, C#) all hint at that.
However, it ignores the fact that Java is light years behind those
languages in *other* non-lambda features.
For example, lambda examples shown at conferences often are like this
(can't remember the exact example):
students.filter(#{student -> student.grade > 65});
Very readable right? And definitely suggesting lots of short lambdas.
But, this is a misleading example.
- the variable is a primitive, so operators can be used
- it doesn't handle null
- it uses a public variable rather than a getter.
By comparison, languages like Groovy, Scala and C# have
- operators on objects (== actually does something sensible, and <, >
are usable)
- better handling of null (eg. the .? and ?: operators or Scala's Option)
- properties (no more pathetic getters)
Thus, in my view, Java lambdas will *inevitably* be *much* more
verbose than those in other languages.
Unless you're going to add these other features to Java! (which you
really should, as you're hobbling lambdas without them...)
Thus the example (adjusted to make the point) above in typical java might be:
students.filter(#{student -> if (student == null ||
student.getName() == null) {return false;} else {return
student.getName().equals("Smith");}});
or formatted more typically:
students.filter(#{student ->
if (student == null || student.getName() == null) {
return false;
} else {
return student.getName().equals("Smith");
}
});
note that for multiline, I too believe the strawman with braces works
best in "Java-style":
students.filter(#(student) {
if (student == null || student.getName() == null) {
return false;
} else {
return student.getName().equals("Smith");
}
});
BTW, in case you want to criticise all that null handling, its
important to realise that just using .equals() and getters rather than
== and properties makes the lambda potentially too long/confusing to
be used inline (there a a lot of end round/curly brackets here):
students.filter(#{student -> student.getName().equals("Smith")});
Grasping just how poor the Java language is in these other features
makes a big difference to understanding how lambdas will be used.
Stephen
More information about the lambda-dev
mailing list