One more syntax option allowing nice control abstraction
Alexander Kochurov
alexander.kochurov at maxifier.com
Mon Jun 20 12:21:57 PDT 2011
David Goodenough suggested to use 'lambda' keyword:
"lambda()(5)
lambda(){return 5;}
lambda(int x,int y) { if (x>y) return x; else return y; }"
Control abstraction may be introduced later in the following way:
to pass lambda to any method taking SAM type as it's last argument, lambda
body should be written in braces after closing bracket, lambda argument
names and types may be given before method parameters in brackets, separated
by colon (if any):
sort(T[], Comparator<T>) may be called with lambda comparator as
T[] array = ...
sort(T a, T b: array) { // a & b are lambda arguments; array is parameter
of 'sort' method
return a.compareTo(b);
}
'lambda' may also be defined as a plain java function (but this won't work
cause type for SAM convertion should be known at compile time):
<T> T lambda(T t) { return t; }
* Pros:
IMHO, that syntax looks very java-ish: see for loop for maps definition
below
<K, V> void forEachEntry(Map<K, V> map, Function2<K, V>*/ f) {
for (Iterator<Entry<K, V>> it =
map.entrySet().iterator();it.hasNext();) {
Entry<K, V> entry = it.next();
f.apply(entry.key, entry.value);
}
}
Map<K, V> m = ...
forEachEntry(K k, V v: m) {
System.out(k + " => " + v);
}
*drawback*: constructor cannot use that syntax: it would be indistinguishable
from subclassing:
new Type() { /* is that labda body or anonymous class body? */ }
Lambdas should be constructed explicitely before passing it to constructor:
new Type(lambda() {return someValue;}) { /* this is not lambda body, it's
anonymous type body*/ };
Alexander Kochurov
More information about the lambda-dev
mailing list