tag:blogger.com,1999:blog-61738361348262815462024-03-25T02:32:59.665-07:00Zdeněk Troníček's blogZdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.comBlogger19125tag:blogger.com,1999:blog-6173836134826281546.post-57759223157312917492011-03-06T01:56:00.000-08:002011-03-09T01:59:18.394-08:00Do we really need <> in the diamond operator?<p>As you may know, one of new features of upcoming Java 7 will be the diamond operator. Purpose of the diamond operator is to simplify instantiation of generic classes. For example, instead of</p>
<code>
List<Integer> p = new ArrayList<Integer>();
</code>
<p>with the diamond operator we can write only</p>
<code>
List<Integer> p = new ArrayList<>();
</code>
<p>and let compiler infer the value of type argument. Nice simplification. But do we really need to write <code><></code>? Isn't <code>new ArrayList()</code> enough? In this article, I will describe the arguments of the <code><></code> proponents and explain why I think that these arguments are not very strong. However, I also describe arguments why we need <code><></code>.</p>
<p>In Java 1.4, we had raw types only:</p>
<code>
List p = new ArrayList();
</code>
<p>Java 5 introduced generics:</p>
<code>
List<Integer> p = new ArrayList<Integer>();
</code>
<p>Many types in Java API were generified and even though we can still use generic types as raw types, there is no reason for this in Java 5 or newer. When generics were introduced, raw types were allowed for backward compatibility so that we could gradually and smoothly adopt generics. For example, code in Java 1.4 can be combined with new generic code because raw and generic types are allowed together. This is also expressed in the JLS (4.8 Raw Types):</p>
<p><span style="font-style:italic;">"The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types."</span></p>
<p>Now let's go back to the diamond operator and ask again: "Do we really need <code><></code>?". The proponents of the <code><></code> syntax say that we need <code><></code> to preserve backward compatibility. Let's look at an <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2011-February/003082.html">example</a> from the coin-dev conference:</p>
<code><pre>
class Foo<X> {
Foo(X x) { }
Foo<X> get(X x) { return this; }
}
class Test {
void test() {
Foo<?> f1 = new Foo(1).get(""); //ok - can pass String where Object is expected
Foo<?> f2 = new Foo<>(1).get(""); //fail - cannot pass String where Integer is expected
}
}
</pre></code>
<p>This shows the difference between <code>new Foo(1)</code> and <code>new Foo<>(1)</code>. Clearly, these two are different and if we changed the semantics of <code>new Foo(1)</code>, it would break backward compatibility. But wait. Backward compatibility with what? Isn't line</p>
<code>
Foo<?> f1 = new Foo(1).get("");
</code>
<p>a little suspicious? It uses generic type in the left part and raw type in the right part. Although it is legal, it is probably either omission or malpractice. And its legality is probably only a side effect of "a concession to compatibility of legacy code".</p>
<p>Let's go further and look at another <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2011-February/003089.html">example</a> from the coin-dev conference. It shows the difference between raw type and parameterized type with the diamond:</p>
<code><pre>
public class X<T> {
public X(T t) { }
public T get() { return null; }
public static int f(String s) { return 1; }
public static int f(Object o) { return 2; }
public static void main(String[] args) {
System.out.println(f(new X<>("").get()));
System.out.println(f(new X("").get()));
}
}
</pre></code>
<p>Let's play with the code a bit. Let's assume that there was a library with the <code>X</code> class:</p>
<code><pre>
public class X {
public X(Object o) { }
public Object get() { return null; }
}
</pre></code>
<p>and some code that compiled against this library:</p>
<code><pre>
public class Client {
static int f(String s) { return 1; }
static int f(Object o) { return 2; }
public static void main(String[] args) {
System.out.println(f(new X("").get()));
}
}
</pre></code>
<p>Then, the library was generified:</p>
<code><pre>
public class X<T> {
public X(T t) { }
public T get() { return null; }
}
</pre></code>
<p>and we compiled the client project against the generified version. Now, if we changed the semantics of <code>new X("")</code> to <code>new X<String>("")</code> (or <code>new X<>("")</code> with the diamond syntax), the code would behave differently. So, the answer to the title question is 'yes'. If we want to stay backward compatible, we need <code><></code> and we cannot put <code>new X("")</code> semantically equal to <code>new X<>("")</code>.</p>
<p>Other questions are how long can Java evolve and remain compatible with concessions to compatibility and whether newcomers to Java will appreciate this.</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com160tag:blogger.com,1999:blog-6173836134826281546.post-57893741200540356442010-08-03T23:26:00.000-07:002010-08-03T23:29:31.027-07:00API evolution with RefactoringNGSee my article <a href="http://www.dzone.com/links/api_evolution_with_refactoringng.html">API evolution with RefactoringNG</a> on dzone.Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com4tag:blogger.com,1999:blog-6173836134826281546.post-52454622754568770192010-06-18T09:21:00.000-07:002010-06-18T10:40:30.669-07:00RefactoringNGRefactoringNG is a flexible and powerful Java refactoring tool, implemented as NetBeans module. Refactoring rules are described as transformations of source abstract syntax trees to destination abstract syntax trees. For example, the rule that rewrites <code>x = x + 1</code> to <code>x++</code> is as follows:
<pre>
// x = x + 1 -> x++
Assignment {
Identifier [name: "x"],
Binary [kind: PLUS] {
Identifier [name: "x"],
Literal [kind: INT_LITERAL, value: 1]
}
} ->
Unary [kind: POSTFIX_INCREMENT] {
Identifier [name: "x"]
}
</pre>
The names and structure of abstract syntax trees are the same as in Sun Java compiler. The tool uses Compiler Tree API (com.sun.*), the formal language model in the JDK API (javax.language.model.*), and NetBeans infrastructure.
For example, if you have ever needed to replace the constructor call with a factory method or add an argument to each method call, you may appreciate how easily such tasks can be done with RefactoringNG:
<h3>Factory method</h3>
<pre>
// new Position(<args>) -> Position.create(<args>)
NewClass {
null,
List<Tree>,
Identifier [name: "Position"],
List<Expression> [id: args],
null
} ->
MethodInvocation {
List<Tree> { },
MemberSelect [identifier: "create"] {
Identifier [name: "Position"]
},
List<Expression> [ref: args]
}
</pre>
<h3>Another argument</h3>
<pre>
// plus (<expr1>, <expr2>) -> plus (<expr1>, <expr2>, 5)
MethodInvocation {
List<Tree> [size: 0],
Identifier [name: "plus"],
List<Expression> [id: args, size: 2]
} ->
MethodInvocation {
List<Tree> [size: 0],
Identifier [name: "plus"],
List<Expression> {
ListItems [ref: args],
Literal [kind: INT_LITERAL, value: 5]
}
}
</pre>
For more information, go to <a href="http://kenai.com/projects/refactoringng">http://kenai.com/projects/refactoringng</a>.
For download, go to <a href="http://kenai.com/projects/refactoringng/downloads">http://kenai.com/projects/refactoringng/downloads</a>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com6tag:blogger.com,1999:blog-6173836134826281546.post-44262124807594811862008-08-19T02:04:00.001-07:002008-08-20T00:55:42.301-07:00Modifier 'for'<h1>Modifier 'for'</h1>
<p>
Method modifier 'for' enables us to declare and call "loop-like" methods.
</p>
<pre class="displaycode"> static for void eachEntry(int[] values, { int ==> void } block) {
for (int p : values) {
block.invoke(p);
}
}
public static void main(String[] args) {
int[] v = { 2, 3, 5, 7, 11 };
for eachEntry(int i : v) {
System.out.println(i);
if (i > 3) {
break;
}
}
}
</pre>
<p>
For example, we can declare a method that iterates through a map:
</p>
<pre class="displaycode"> static for <K, V> void eachMapEntry(Map<K, V> dict,
{ K, V ==> void } block) {
for (Map.Entry<K, V> entry : dict.entrySet()) {
block.invoke(entry.getKey(), entry.getValue());
}
}
public static void main(String[] args) {
Map<String, String> dict = new HashMap<String, String>();
...
for eachMapEntry(String k, String v : dict) {
System.out.println(k + ": " + v);
}
}
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com8tag:blogger.com,1999:blog-6173836134826281546.post-79206883419311997272008-08-19T01:59:00.000-07:002008-09-19T02:06:47.089-07:00Nonlocal transfer<h1>Nonlocal transfer</h1>
<p>
In unrestricted closures, we can use the <code>break</code>, <code>continue</code>, and
<code>return</code> statements.
</p>
<pre class="displaycode"> for (int i = 0; i < 5; i++) {
System.out.println(i);
if (i == 2) { ==> break; }.invoke();
}
</pre>
<p>
These statements are always lexically bound, i.e. they are bound in the context in which
the closure is declared (as opposite to invoked). So, the following code will print numbers
from <1,10> that are not multiples of 3.
</p>
<pre class="displaycode"> static void m(int i, { int => boolean } cond, { ==> void } block) {
if (cond.invoke(i)) {
block.invoke();
}
}
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
// continue is bound to the for loop
m(i, { int i => i % 3 == 0 }, { ==> continue; });
System.out.println(i);
}
}
</pre>
<p>
The <code>return</code> statement returns from the bound method.
</p>
<pre class="displaycode"> static int m1() {
// return here means "return from m1"
m2({ double d ==> if (d < 0.5) return 1; });
return 0;
}
static void m2({ double ==> void } p) {
// the closure invocation can cause return from m1
p.invoke(Math.random());
}
</pre>
<p>
If the bound method is not active at the time when we call the closure with the <code>return</code>
statement, we will get the UnmatchedTransfer exception. For example:
</p>
<pre class="displaycode"> // any type can be used as the return type of p in this
// example because the closure always returns earlier
// so, p can be declared also as static { ==> int } p;
static { ==> boolean } p;
static int m1() {
p = { ==> return 1; };
return 0;
}
public static void main(String[] args) {
System.out.println(m1());
System.out.println(p.invoke());
}
</pre>
<p>
Unrestricted closures are useful when declaring "statement-like" methods.
</p>
<pre class="displaycode"> static void withLock(Lock lock, { ==> void } block) {
try {
lock.lock();
block.invoke();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Lock guard = new ReentrantLock();
double d = Math.random();
withLock(guard) {
if (d < 0.5) {
return;
}
...
}
}
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com10tag:blogger.com,1999:blog-6173836134826281546.post-18407579350910210882008-03-29T05:50:00.000-07:002008-03-29T06:29:34.243-07:00Method references (Implementation Issue)<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Method references (Implementation Issue)</h1>
<p>
Each method reference is transformed to a closure:
</p>
<pre class="displaycode">
// Math#sqrt(double) will be transformed to { double d => Math.sqrt(d) }
{ double => double } sqrt = Math#sqrt(double);
</pre>
<p>
Instance method references are transformed in a similar way.
</p>
<pre class="displaycode">
Circle c = new Circle();
{ => void } p = c#draw(); // the same as { => c.draw(); }
</pre>
<pre class="displaycode">
{ Circle => void } p = Circle#draw(); // { Circle c => c.draw(); }
</pre>
<p>
Let us have a look at another example. We declare class <code>Box</code>:
</p>
<pre class="displaycode">
public class Box<T> {
T v;
public Box(T v) {
this.v = v;
}
public T getValue() {
return v;
}
public void print() {
System.out.println("Box: " + v);
}
}
</pre>
<p>
and refer to the <code>print</code> method:
</p>
<pre class="displaycode">
// Box#print() will be transformed to { Box<Integer> box => box.print(); }
{ Box<Integer> => void } p = Box#print();
</pre>
<p>
Reference to a generic method will be replaced by a closure as follows:
</p>
<pre class="displaycode">
public class Generic {
public static <T> Box<T> copy(Box<T> b) {
return new Box<T>(b.getValue());
}
}
</pre>
<pre class="displaycode">
// Generic#copy(Box<Integer>) will be transformed to
// { Box<Integer> box => Generic.copy(box) }
{ Box<Integer> => Box<Integer> } boxCopy = Generic#copy(Box<Integer>);
</pre>
<p>
<b><i>I do not want closures in Java because they are not simple.</i></b><br/>
This argument is wrong. We should always weigh all pros and cons. Closures are not simple. But is software development in Java simple? What should I know to be capable to develop software in Java? Knowledge of the Java programming language is clearly not enough. One should also know some Java technologies and frameworks. And are they simple? Are JPA, EJB, JAX-WS, Hibernate, or Spring (to name a few) simple? Apparently no, so it does not make sense to reject closures just for this reason.
</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com10tag:blogger.com,1999:blog-6173836134826281546.post-8020582764712849982008-03-20T12:44:00.001-07:002008-03-20T12:50:59.949-07:00Method References (version 2008-03-17)<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Method references (version 2008-03-17)</h1>
<p>
The compiler prototype (available at <a href="http://www.javac.info/">http://www.javac.info</a>)
comes with <i>method references</i> (also known as eta expansion).
The method references are written as follows: <i>ClassName # methodName ( listOfArgumentTypes )</i>.
</p>
<p>
A method reference can be assigned to a function variable:
</p>
<pre class="displaycode">
{ String => int } parseInt = Integer#parseInt(String);
int x = parseInt.invoke("42");
</pre>
<p>
We can use the covariant return:
</p>
<pre class="displaycode">
// Integer.valueOf() returns Integer
{ int => Number } p = Integer#valueOf(int);
System.out.println(p.invoke(97));
</pre>
<p>
And the contravariant arguments:
</p>
<pre class="displaycode">
class MyClass {
static Integer print(Object o) {
return Integer.valueOf(o.hashCode());
}
public static void main(String[] args) {
{ String => Number } pp = MyClass#print(Object);
System.out.println(pp.invoke("hi"));
}
}
</pre>
<p>
An instance method can be referenced in two ways. Either we reference a method on a given object:
</p>
<pre class="displaycode">
class Box {
private int x;
Box(int x) {
this.x = x;
}
int getX() {
return x;
}
}
public class InstanceMethod {
public static void main(String[] args) {
Box p = new Box(10);
{ => int } getX = p#getX();
System.out.println(getX.invoke());
}
}
</pre>
<p>
Or we reference just a method. Then the function type has an additional argument: the object on which the method is called.
</p>
<pre class="displaycode">
{ Box => int } getX = Box#getX(); // additional argument of type Box
Box p = new Box(10);
System.out.println(getX.invoke(p));
</pre>
<p>
The method is selected at runtime according to the object supplied as argument.
So, in the following example, the <code>toString</code> method from <code>String</code> is called.
</p>
<pre class="displaycode">
{ Object => String } toString = Object#toString();
System.out.println(toString.invoke("hi"));
</pre>
<p>
Generic methods are also supported:
</p>
<pre class="displaycode">
{ String => Set<String> } singleton =
Collections#<String>singleton(String);
Set<String> set = singleton.invoke("single");
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com26tag:blogger.com,1999:blog-6173836134826281546.post-83049533920255302162008-02-25T01:19:00.000-08:002008-03-20T12:44:14.607-07:00Control Abstraction (version 2008-02-22)<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Control Abstraction (version 2008-02-22)</h1>
<p>
<i>In this post, I will describe new features of version 2008-02-22 of the compiler prototype. It can be downloaded from
<a href="http://www.javac.info/">http://www.javac.info</a>.
</i>
</p>
<p>
1. <code>java.lang.Unreachable</code> was renamed to <code>java.lang.Nothing</code>.
</p>
<p>
2. Annotation <code>@Shared</code> was added. It may annotate a variable bound in a closure. For example:
</p>
<pre class="displaycode">
static void doTwice({ => void } block) {
block.invoke();
block.invoke();
}
public static void main(String[] args) {
@Shared int x = 10;
doTwice({ => System.out.println(x++); });
}
</pre>
<p>
We should always annotate bound variables with this annotation because bound variables are very different from ordinary local variables.
</p>
<p>
3. Closures can use recursion. Now we can use the function variable within a closure that is used to initialize this variable.
</p>
<pre class="displaycode">
{ int => int } sum = { int n => n == 1 ? 1 : n + sum.invoke(n - 1) };
</pre>
<p>
4. Unrestricted closures were partially implemented. In an urestricted closure we can use the <code>return</code>, <code>break</code>, and <code>continue</code> statements. Unrestricted closures use <code>==></code> instead of <code>=></code>.
</p>
<pre class="displaycode">
{ int ==> int } neg = { int x ==> -x };
</pre>
<p>
5. A method that accepts an unrestricted closure as the last argument can be called using the <i>control invocation syntax</i>:
<pre class="displaycode">
public static void simple({ ==> void } block) {
block.invoke();
block.invoke();
}
public static void main(String[] args) {
simple() {
System.out.println("vrr!");
}
}
</pre>
<p>
The method may have more than one parameter:
</p>
<pre class="displaycode">
public static void profile(String s, { ==> void } block) {
System.out.printf(">>> %s: %s%n", s, System.nanoTime());
block.invoke();
System.out.printf("<<< %s: %s%n", s, System.nanoTime());
}
public static void main(String[] args) {
@Shared long f = 1;
profile("factorial") {
for (int i = 2; i <= 59; i++) {
f *= i;
}
}
}
</pre>
<p>
The closure used as the last argument can have parameters. They are declared before arguments of the method and are separated from them by colon (although the syntax is similar to the enhanced <code>for</code> loop, the colon here has another meaning):
</p>
<pre class="displaycode">
public static void control(int x, { int ==> void } block) {
block.invoke(x);
}
public static void main(String[] args) {
// ordinary syntax
control(1, { int i ==> System.out.println(i); });
// control invocation syntax
control(int i : 2) {
System.out.println(i);
}
}
</pre>
<p>
If the closure has more parameters, they are separated by comma:
</p>
<pre class="displaycode">
public static void controlTwo(int x, { int, int ==> void } block) {
block.invoke(x, x + 1);
block.invoke(x + 2, x);
}
public static void main(String[] args) {
// closure parameters are separated by comma
controlTwo(int i, int j : 2) {
System.out.println(i * j);
}
}
</pre>
<p>
This enables us to define new "control statements" without modifying the language. For example, we can add "statement" <code>with</code> that closes a given closeable at the end (the code is derived from the prototype sources):
</p>
<pre class="displaycode">
public static <T extends Closeable> void with(T t, { T ==> void } block) {
try {
block.invoke(t);
} finally {
try {
t.close();
} catch (IOException e) {
// ignore exception
}
}
}
public static void main(String[] args) {
// class MyCloseable implements Closeable
with (MyCloseable in : new MyCloseable()) {
//...
}
}
</pre>
<p>
<b><i>Why Java cannot remain simple? Do we need new control statements?</i></b><br/>
Many people like simplicity (I am one of them). But Java must evolve if we do not want it to become outdated. In addition, the hardware is changing and these changes will probably change programming languages used in software development. For information how the hardware is changing, I recommend the article <a href="http://www.gotw.ca/publications/concurrency-ddj.htm">The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software</a>. If you are curious how future programming languages may look like, have a look at <a href="http://www.research.ibm.com/x10/">x10</a> being developed at IBM. I also recommend the post <a href="http://gafter.blogspot.com/2008/01/is-java-dying.html">Is Java dying?</a>
</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com19tag:blogger.com,1999:blog-6173836134826281546.post-38009780828139667472008-01-07T00:37:00.000-08:002008-02-28T10:52:50.569-08:00Usage<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Usage</h1>
<p>
<i>In this post, I express my opinion on many places. For example, when I say "it is more intuitive...", I mean
"in my opinion, it is more intuitive...".</i>
</p>
<p>
As we already mentioned, closures are transformed to anonymous inner classes at compile time. So, all we can do
with closures, can be done with inner classes as well. However, the access to local variables may require a little effort.
For example, the code
</p>
<pre class="displaycode">
int x = 4;
{ => System.out.println(++x); }.invoke();
</pre>
<p>
can be rewritten without closures as follows:
</p>
<pre class="displaycode">
final int[] x = { 4 };
new javax.lang.function.V() {
public void invoke() {
System.out.println(++x[0]);
}
}.invoke();
</pre>
<p>
Even if closures do not increase the power of language, in many cases they are more concise and intuitive than other means.
They are a natural choice when we want to parameterize an algorithm with a function. For example, sorting
may be parameterized with a comparison function:
</p>
<pre class="displaycode">
Integer[] primes = { 19, 23, 2, 11, 17, 31, 5, 13 };
Arrays.sort(primes, { Integer x, Integer y => y.compareTo(x) });
</pre>
<p>
Here, it is more intuitive to use a function argument than the
<code>Comparator</code> interface because the purpose of the argument is only
to compare two values.
</p>
<p>
One should also prefer closures for predicates because predicate is a function:
</p>
<pre class="displaycode">
static <T> void selectAndPrint(Iterable<T> items, { T => boolean } cond) {
for (T item: items) {
if (cond.invoke(item)) {
System.out.println(item);
}
}
}
public static void main(String[] args) {
List<String> cities = Arrays.asList(
"Prague", "San Francisco", "Moscow", "New York", "Paris");
int max = ...;
// will print cities that are not longer than max
selectAndPrint(cities, { String s => s.length() <= max });
char c = ...;
// will print cities that contain character c
selectAndPrint(cities, { String s => s.indexOf(c) >= 0 });
}
</pre>
<p>
Function types can also be used to describe the input of algorithm. For example, a method that returns the size
of area under the function curve should have a function argument:
</p>
<pre class="displaycode">
static double determineFiniteIntegral(
double from, double to, { double => double } func) {
double area;
//...
return area;
}
</pre>
<p>
Another usage is in a method that takes a block of code as argument. For example, the <code>execute</code> method
takes a block that should be performed in a separate thread:
</p>
<pre class="displaycode">
ExecutorService pool = Executors.newFixedThreadPool(5);
pool.execute({ => System.out.println("thinking..."); });
</pre>
<p>
Again, it is more intuitive and logical to pass a block of code than an object that implements <code>Runnable</code>.
</p>
<p>
Closures enable us to write methods that behave in a similar way as the <i>foreach</i> loop:
</p>
<pre class="displaycode">
static void forEach(int[] nums, { int => void } block) {
for (int n: nums) {
block.invoke(n);
}
}
public static void main(String[] args) {
int[] p = { 5, 1, 3, 4, 2 };
int sum = 0;
forEach(p, { int n => sum += n; }); // will sum up the numbers in array
int min = Integer.MAX_VALUE;
forEach(p, { int n => if (n < min) min = n; }); // will find the minimum
}
</pre>
<p>
For example, we can implement a method that performs an operation on each map entry:
</p>
<pre class="displaycode">
static <K, V> void forEachEntry(Map<K, V> map, { K, V => void } block) {
for (Map.Entry<K, V> entry: map.entrySet()) {
block.invoke(entry.getKey(), entry.getValue());
}
}
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
//...
forEachEntry(map, {
Integer key, String value =>
System.out.println(key + ": " + value); });
}
</pre>
<p>
We can also use closures to implement the <i>visitor design pattern</i> in a simple fashion:
</p>
<pre class="displaycode">
class Node {
int value;
Node left, right;
}
class Tree {
Node root;
//...
void visitPreOrder({ int => void } block) {
visitPreOrder(root, block);
}
void visitPreOrder(Node p, { int => void } block) {
if (p != null) {
block.invoke(p.value); // first perform the operation on this node
visitPreOrder(p.left, block); // then on the left subtree
visitPreOrder(p.right, block); // and then on the right subtree
}
}
}
public class TreeOperations {
public static void main(String[] args) {
Tree tree = ...;
List<Integer> nums = new ArrayList<Integer>();
// will add the numbers to the list
tree.visitPreOrder({ int v => nums.add(v); });
//...
}
}
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com14tag:blogger.com,1999:blog-6173836134826281546.post-13454728220786400932008-01-07T00:09:00.000-08:002008-02-28T10:53:08.419-08:00Completion Transparency<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Completion Transparency</h1>
<p>
<i>Completion transparency</i> enables us to create methods that transparently return the result of a closure
which is passed as argument. For example:
</p>
<pre class="displaycode">
static <T> T withLock(Lock lock, { => T } block) {
lock.lock();
try {
return block.invoke();
} finally {
lock.unlock();
}
}
</pre>
<p>
We can pass to the <code>withLock</code> method a block that returns any value. For example:
</p>
<pre class="displaycode">
Lock lock = new ReentrantLock();
Integer i = withLock(lock, { => Integer.valueOf(42) });
</pre>
<p>
Due to completion transparency, we can also use a block that does not return anything (i.e. a block of type <code>{ => void }</code>):
</p>
<pre class="displaycode">
withLock(lock, { => System.out.println("mining..."); });
</pre>
<p>
And even a block that cannot complete normally, i.e. throws exception
(in this case only unchecked exceptions are allowed):
</p>
<pre class="displaycode">
withLock(lock, { => throw new NullPointerException(); });
</pre>
<p>
To allow checked exceptions as well, we can use exceptions transparency:
</p>
<pre class="displaycode">
static <T, throws E> T withLockEx(Lock lock, { => T throws E} block)
throws E {
lock.lock();
try {
return block.invoke();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
try {
Lock lock = new ReentrantLock();
withLockEx(lock, { => throw new Exception(); });
} catch (Exception e) { e.printStackTrace(); }
}
</pre>
<h1>Implementation issue</h1>
<p>
Let us recall that each closure is converted to an instance of interface. For example, a closure
<code>{ => System.out.println("buff"); }</code> is converted to an instance of <code>V</code>:
</p>
<pre class="displaycode">
public interface V {
void invoke();
}
</pre>
<p>
To achieve completion transparency, the compiler is allowed to use <code>Void</code> instead of <code>void</code>.
For example, the code
</p>
<pre class="displaycode">
withLock(lock, { => System.out.println("miaow"); });
</pre>
<p>
will be transformed approximately as follows:
</p>
<pre class="displaycode">
withLock(lock, new javax.lang.function.O() {
public Void invoke() {
System.out.println("miaow");
return null;
}
}
</pre>
<p>
In case of closures that do not complete normally, the invoke method returns <code>java.lang.Unreachable</code>
which is a special class that is considered a subclass of all classes.
This means that an <code>Unreachable</code> may be assigned to any reference variable.
For example, the statement
</p>
<pre class="displaycode">
Integer i = { => throw new NullPointerException(); }.invoke();
</pre>
<p>
will be transformed roughly as follows:
</p>
<pre class="displaycode">
Integer i = new javax.lang.function.O() {
public Unreachable invoke() { throw new NullPointerException(); }
}.invoke();
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com0tag:blogger.com,1999:blog-6173836134826281546.post-85122981547192512142007-12-28T10:35:00.001-08:002008-02-28T10:53:25.955-08:00Closures Sources<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Closures sources</h1>
<ul>
<li>Neal Gafter's blog:
<ul>
<li><a href="http://gafter.blogspot.com/2007/01/definition-of-closures.html">Definition of Closures</a></li>
<li><a href="http://gafter.blogspot.com/2006/09/debate-over-closures-for-java.html">The Debate over Closures for Java</a></li>
</ul>
</li>
<li>Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé: <a href="http://www.javac.info">Closures for Java (v0.5).</a>
This is known as BGGA proposal.
</li>
<li><a href="http://www.javac.info/consensus-closures-jsr.html">JSR Proposal: Closures for Java.</a></li>
<li><a href="http://www.parleys.com/display/PARLEYS/An+update+on+Java+Closures">Closures for Java (video)</a></li>
<li><a href="http://www.parleys.com/display/PARLEYS/Neal+Gafter+JavaPolis+2006+interview">Neal Gafter JavaPolis 2006 interview</a></li>
<li><a href="http://www.artima.com/lejava/articles/neal_gafter_closures.html">An interview with Neal Gafter on Artime.</a></li>
<li><a href="http://www.parleys.com/display/PARLEYS/The+Closures+Controversy">Joshua Bloch presentation at JavaPolis 2007</a></li>
<li><a href="http://www.ibm.com/developerworks/java/library/j-jtp04247.html">The closures debate.</a></li>
<li>Mark Mahieu's blog:
<ul>
<li><a href="http://markmahieu.blogspot.com/2007/12/currying-and-partial-application-with.html">Currying and Partial Application with Java Closures</a></li>
<li><a href="http://markmahieu.blogspot.com/2007/12/unrestricted-closure-example.html">An unrestricted closure example</a></li>
</ul>
</li>
<li><a href="http://www.juixe.com/techknow/index.php/2007/01/29/java-7-the-closure-debate/">Java 7: The Closure Debate</a></li>
<li><a href="http://eclipsezone.com/forums/thread.jspa?messageID=92099076">When is a closure not a closure?</a></li>
<li><a href="http://www.blog.dannynet.net/archives/87">Danny's blog.</a></li>
<li><a href="http://lucdup.blogspot.com/">Luc Duponcheel's blog.</a></li>
</ul>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com13tag:blogger.com,1999:blog-6173836134826281546.post-54258228696951161582007-12-28T10:32:00.000-08:002008-02-28T10:53:46.514-08:00Advanced Features<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Advanced features</h1>
<p>
A function type can be used as type parameter:
</p>
<pre class="displaycode">
public static void main(String[] args) {
List<{ int, int => int }> operations =
new ArrayList<{ int, int => int }>();
operations.add({ int x, int y => x + y });
operations.add({ int x, int y => x | y });
int[][] param = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
for (int[] p: param) {
for ({ int, int => int } op : operations) {
System.out.println(op.invoke(p[0], p[1]));
}
}
}
</pre>
<p>
A closure can return another closure:
</p>
<pre class="displaycode">
{ String => { int => String } } concat =
{ String s =>
{ int n => String r = ""; for ( ; n > 0; n--) r += s; r } };
</pre>
<p>
Function concat takes a single string argument and returns a function that takes a single integer argument and returns string.
</p>
<pre class="displaycode">
{ int => String } concatABC = concat.invoke("ABC");
String result = concatABC.invoke(3);
</pre>
<p>
Each function that takes multiple arguments can be transformed into a function that takes a single argument. This transformation is
called <i>currying</i>. For example, function plus can be transformed into anotherPlus:
</p>
<pre class="displaycode">
{ int, int => int } plus = { int x, int y => x + y };
{ int => { int => int } } anotherPlus = { int x => { int y => x + y } };
int threePlusFour = anotherPlus.invoke(3).invoke(4);
</pre>
<p>
The reverse transformation is called <i>uncurrying</i>. Currying and uncurrying are used in functional programming.
For more examples of functional programming in Java, see <a href="http://lucdup.blogspot.com/">Luc Duponcheel's blog</a>.
</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com5tag:blogger.com,1999:blog-6173836134826281546.post-66961043972069944612007-12-28T10:24:00.000-08:002008-02-28T10:53:58.280-08:00Exceptions<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Exceptions</h1>
<p>
Closures are allowed to throw exceptions. We use the <code>throws</code> keyword to declare which exceptions are
thrown by a closure:
</p>
<pre class="displaycode">
{ long => void throws InterruptedException } wait =
{ long millis => Thread.sleep(millis); };
try {
wait.invoke(2000);
System.out.println("hi");
} catch (InterruptedException e) { e.printStackTrace(); }
</pre>
<p>
A closure may throw more than one exception:
</p>
<pre class="displaycode">
try {
FileOutputStream fos = new FileOutputStream("primes");
try {
{ int, long =>
void throws IOException, InterruptedException } writeAndWait =
{ int value, long millis =>
fos.write(value); Thread.sleep(millis); };
writeAndWait.invoke(17, 2000);
System.out.println("first");
writeAndWait.invoke(19, 2000);
System.out.println("second");
} finally { fos.close(); }
} catch (IOException | InterruptedException e) { e.printStackTrace(); }
</pre>
<p>
When we assign a closure to a variable of function type, the closure must not throw more than is declared in
the function type.
</p>
<pre class="displaycode">
// constructor FileWriter throws IOException which is a subclass of
// Exception
{ String => void throws Exception } truncate =
{ String name => new FileWriter(name).close(); };
{ => double throws Exception } next =
{ => Math.random() }; // Math.random() does not throw any exception
</pre>
<hr/>
<h1>Exception Transparency</h1>
<p>
If we pass a closure that throws exceptions to some method, we might want these exceptions are propagated from the method.
If we used ordinary type parameter for exception, we could have passed in only a block that throws one exception.
But what if we want to accept a block that throws any number of exceptions and we want exceptions are transparently
propagated to the caller? We have to use <i>exception type parameters</i>.
The exception type parameter is declared using the <code>throws</code> keyword and stands for any number of exceptions.
</p>
<pre class="displaycode">
// method performTwice throws the same exceptions as the block passed in
static <throws E> void performTwice({ => void throws E } block) throws E {
block.invoke();
block.invoke();
}
static void passBlockThrowingNoExceptions() {
performTwice({ => System.out.println("no exception..."); });
}
static void passBlockThrowingOneException() {
try {
// the block passed to performTwice throws one exception
// (InterruptedException)
// the compiler checks that we catch this exception
performTwice({ =>
System.out.println("waiting..."); Thread.sleep(2000); });
} catch (InterruptedException e) { e.printStackTrace(); }
}
static void passBlockThrowingMoreExceptions() {
try {
// the block passed to performTwice throws two exceptions
// (InterruptedException and IOException)
// the compiler checks that we catch these exceptions
performTwice({ => Thread.sleep(2000); new FileWriter("x").close(); });
} catch (InterruptedException | IOException e) { e.printStackTrace(); }
}
</pre>
<p>
If we do not want to propagate exceptions, we can invoke a closure in the try block:
</p>
<pre class="displaycode">
static <throws E> void logAndPerform(
String desc, { => void throws E } block) {
System.out.printf("start: %s...%n", desc);
try {
block.invoke();
} catch (Exception e) { e.printStackTrace(); }
System.out.printf("end: %s%n", desc);
}
public static void main(String[] args) {
logAndPerform("doing nothing", { => System.out.println("hi"); });
logAndPerform("sleeping", { => Thread.sleep(2000); });
logAndPerform("sleeping and truncating",
{ => Thread.sleep(2000); new FileWriter("x").close(); });
}
</pre>
<hr/>
<h2>Exercises</h2>
<ol>
<li>Fill in the type of p.
<pre class="displaycode">
static void m() throws FileNotFoundException, InterruptedException {
//...
}
public static void main(String[] args) {
p = { => m(); };
try {
p.invoke();
} catch (FileNotFoundException | InterruptedException e) {
e.printStackTrace();
}
}
</pre>
</li>
<li>Declare method forEach that performs an operation on each item of a collection. The operation is described by a closure
and may throw an exception (one or more).
</li>
</ol>
<h2>Solutions</h2>
<pre class="displaycode">
{ => void throws FileNotFoundException, InterruptedException } p =
{ => m(); };
</pre>
<pre class="displaycode">
static <T, throws E> void forEach(
Iterable<T> items, { T => void throws E } block) throws E {
for (Iterator<T> it = items.iterator(); it.hasNext(); ) {
block.invoke(it.next());
}
}
public static void main(String[] args) {
List<String> nums = Arrays.asList("first", "second", "third");
forEach(nums, { String s => System.out.println(s); });
}
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com0tag:blogger.com,1999:blog-6173836134826281546.post-34632172520013411112007-12-28T10:21:00.000-08:002008-02-28T10:54:10.937-08:00Closure Conversion<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Closure Conversion</h1>
<p>
A closure can be assigned to a variable of compatible interface type. A compatible interface type must have a single method with
a compatible return type and compatible argument types. For example:
</p>
<pre class="displaycode">
interface IntPlus {
int add(int x, int y);
}
IntPlus plus = { int x, int y => x + y };
</pre>
<p>
In such case, a closure is converted to an instance of anonymous class that implements the given interface:
</p>
<pre class="displaycode">
IntPlus plus = new IntPlus() {
public int add(int x, int y) { return x + y; }
};
</pre>
<p>
Then, we call the closure by the interface method:
</p>
<pre class="displaycode">
int sum = plus.add(5, 6);
</pre>
<p>
This allows us to use a closure instead of anonymous subclass of interface with a single method.
For example, the closure conversion can create an instance of Runnable:
</p>
<pre class="displaycode">
new Thread({ => System.out.println("hi"); }).start();
</pre>
<p>
Sometimes we can use the closure conversion even if the interface has more than one method. It is in case when all but one
method are implemented in Object. The closure is then converted to a single remaining method.
For example, interface Comparator contains two methods:
<code>compare()</code> and <code>equals()</code>.
Method <code>equals()</code> is in Object and so the closure is converted
to method <code>compare()</code>.
</p>
<pre class="displaycode">
String[] girls = { "Jane", "Eva", "Sarah", "Alice" };
Arrays.sort(girls,
{ String s1, String s2 =>
int r = s1.length() - s2.length(); r == 0 ? s1.compareTo(s2) : r
});
</pre>
<hr/>
<h2>Exercises</h2>
<ol>
<li>Declare interface HashCalculator.
<pre class="displaycode">
HashCalculator hc =
{ String s1, String s2 => s1.hashCode() ^ s2.hashCode() };
System.out.println(hc.hash("elephant", "giraffe"));
</pre>
</li>
<li>Use a closure to define Comparator which sort numbers descendingly.
<pre class="displaycode">
Integer[] wages = { 1200, 4500, 850, 1500, 990 };
Arrays.sort(wages, );
</pre>
</li>
<li>Sort an array of strings and count the number of comparisons.</li>
</ol>
<h2>Solutions</h2>
<pre class="displaycode">
interface HashCalculator {
int hash(String s1, String s2);
}
</pre>
<pre class="displaycode">
Integer[] wages = { 1200, 4500, 850, 1500, 990 };
Arrays.sort(wages, { Integer i, Integer j => j.compareTo(i) });
</pre>
<pre class="displaycode">
String[] countries = {
"France", "Czech Republic", "Poland", "Hungary", "Germany"
};
int c = 0;
Arrays.sort(countries, { String s1, String s2 => c++; s1.compareTo(s2) });
System.out.println("number of comparisons: " + c);
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com7tag:blogger.com,1999:blog-6173836134826281546.post-36123999442091503242007-12-28T10:17:00.001-08:002008-02-28T10:54:42.235-08:00Covariant Return and Contravariant Arguments<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h2>Covariant Return and Contravariant Arguments</h2>
<p>
As we know, to a variable of function type may be assigned a closure with compatible return type
and compatible argument types. "Compatible return type" means that the type is either the same as in function type or is
a subclass of this type (return types are <i>covariant</i>).
</p>
<pre class="displaycode">
{ => Number } p1 =
{ => Integer.valueOf(19) }; // Integer is a subclass of Number
{ => Number } p2 =
{ => Double.valueOf(1.25) }; // Double is a subclass of Number
</pre>
<p>
"Compatible argument type" means that the argument type is either the same as in function type or is a superclass of this type
(argument types are <i>contravariant</i>).
</p>
<pre class="displaycode">
{ String => void } p =
// Object is a superclass of String
{ Object o => System.out.println(o); };
</pre>
<p>
We can combine covariant return with contravariant arguments:
</p>
<pre class="displaycode">
{ String => Number } p = { Object o => Integer.valueOf(o.hashCode()) };
System.out.println(p.invoke("haf"));
</pre>
<p>
These rules define hierarchy on function types. So a function type might be a subtype or supertype of another function type.
For example, <code>{ => Integer }</code> is a subtype of <code>{ => Number }</code> and <code>{ String => void }</code> is
a supertype of <code>{ Object => void }</code>. As for class types, to a variable of function type may be assigned
an object (closure) of its type or any subtype.
</p>
<p>
<b><i>What is meant by covariant and contravariant?</i></b><br/>
Let S and T be two types (classes or function types) such that S is a subtype of T. If method m of T is overridden in S, then
the corresponding types from the m's signature can either preserve the relationship between S and T (i.e. the type used in S is
a subtype of the
corresponding type in T), reverse this relationship (i.e. the type used in S is a supertype of that in T), or neither
preserve nor reverse this relationship. If they preserve the relationship of S and T, we say they are <i>covariant</i>, and if
they reverse the relationship of S and T, we say they are <i>contravariant</i>.
</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com8tag:blogger.com,1999:blog-6173836134826281546.post-54004590954516052442007-12-28T10:13:00.000-08:002008-02-28T10:54:54.520-08:00Local Variables<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Access to Local Variables</h1>
<p>
So far, closures were a concise analogy to anonymous inner classes. But they offer more. In inner classes, you can access
a variable from enclosing scope only if it is final. For closures, there is no such restriction:
</p>
<pre class="displaycode">
public static void main(String[] args) {
int x = 4;
{ => void } printX =
{ => System.out.println(x); }; // x is a free variable here
x++;
printX.invoke(); // will print 5
}
</pre>
<p>
In function printX, x is a free variable because it is not declared in the printX's block of code
(it is neither a parameter nor a local variable
in this block). We can access and change free variables:
</p>
<pre class="displaycode">
int x = 100;
{ => int } nextX = { => ++x };
System.out.println(nextX.invoke()); // will print 101
System.out.println(nextX.invoke()); // will print 102
x = 200;
System.out.println(nextX.invoke()); // will print 201
</pre>
<p>
A block of code is packed with variables of the enclosing scope, i.e. the scope where the block is declared.
This is where the name "closure" comes from. For example, the following block of code
will always work with variable x in the main method:
</p>
<pre class="displaycode">
static void doTwice({ => void } block) {
block.invoke(); // will print 10
int x = 20;
block.invoke(); // will print 11
System.out.println(x); // will print 20
}
public static void main(String[] args) {
int x = 10;
// the block is "packed" with variable x
doTwice({ => System.out.println(x++); });
}
</pre>
<p>
A closure can use variables of the enclosing scope even if this scope
is not active at the time of closure invocation.
For example, a closure can use local variables of a method after return from this method:
</p>
<pre class="displaycode">
static { => int } makeSum() {
int n = 1, s = 0;
// the following closure uses local variables n and s
return { => s += n; n++; s };
}
public static void main(String[] args) {
{ => int } sum = makeSum();
System.out.println(sum.invoke()); // will print sum 0 + 1
System.out.println(sum.invoke()); // will print sum 0 + 1 + 2
System.out.println(sum.invoke()); // will print sum 0 + 1 + 2 + 3
}
</pre>
<p>
If we declare n and s local in a closure, we will get different results:
</p>
<pre class="displaycode">
static { => int } makeSumWrong() {
return { => int n = 1, s = 0; s += n; n++; s };
}
public static void main(String[] args) {
{ => int } sum = makeSumWrong();
System.out.println(sum.invoke()); // will print sum 0 + 1
System.out.println(sum.invoke()); // will print sum 0 + 1
System.out.println(sum.invoke()); // will print sum 0 + 1
}
</pre>
<p>
Variables n and s are now local in a closure, so they are initialized upon each invocation of this closure.
</p>
<p>
Reference <code>this</code> in a closure has the same meaning as <code>this</code> in enclosing scope.
</p>
<pre class="displaycode">
public class TestThis {
String s = "hello";
void test() {
String s = "hi";
{ => System.out.println(this.s); }.invoke(); // will print "hello"
}
public static void main(String[] args) {
new TestThis().test();
}
}
</pre>
<hr/>
<h1>Implementation Issue</h1>
<p>
Local variables that are accessed from a closure are allocated on the heap, so that they are available even when we exit
the block they are declared in.
</p>
<hr/>
<h2>Exercises</h2>
<ol>
<li>Determine the output.
<pre class="displaycode">
class ClosureWithThis {
int x = 1;
void tryThis() {
new Invoker().tryThis({ int x =>
System.out.println(x);
System.out.println(this.x);
});
}
public static void main(String[] args) {
new ClosureWithThis().tryThis();
}
}
class Invoker {
int x = 2;
void tryThis({ int => void } p) {
p.invoke(3);
}
}
</pre>
</li>
<li>Determine the output.
<pre class="displaycode">
static void m({ => int } c1, { => int } c2) {
System.out.println(c1.invoke());
System.out.println(c2.invoke());
}
public static void main(String[] args) {
int i = 1;
m({ => ++i }, { => --i });
}
</pre>
</li>
</ol>
<h2>Solutions</h2>
<ol>
<li>x refers to the argument and this.x refers to field x of the ClosureWithThis instance. Thus, the first println will print
3 and the second will print 1.
</li>
<li>Closures <code>{ => ++i }</code> and <code>{ => --i }</code> refer to the same variable i.
Thus, the first println will print 2 and the second will print 1.
</li>
</ol>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com10tag:blogger.com,1999:blog-6173836134826281546.post-73138746202373352842007-12-28T10:10:00.000-08:002008-02-28T10:55:15.870-08:00Function Types<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Function Types</h1>
<p>
Function types are used when we want to refer to closures. We can declare a variable of function type and assign to it
a reference to a closure.
A <i>function type</i> is written as follows: { <i>formal parameters</i> => <i>return type</i> }. Formal parameters are
optional. The return type can be any type or void.
For example, <code>{ int, String => void }</code> means a function with two arguments (int and String) and return type void.
Any function with a compatible list of argument types and compatible return type can be assigned to a variable of function type.
</p>
<pre class="displaycode">
public class DeepThought {
// { => int } means a function with no arguments and return type int
static { => int } answer = { => 42 };
public static void main(String[] args) {
int i = answer.invoke();
System.out.println(i);
}
}
</pre>
<p>
A function with one int argument and return type String:
</p>
<pre class="displaycode">
{ int => String } toBinary = { int x => Integer.toBinaryString(x) };
String binary11 = toBinary.invoke(11); // will return 1011
</pre>
<p>
A function with no arguments and return type void:
</p>
<pre class="displaycode">
{ => void } sayHello = { => System.out.println("Hello"); };
sayHello.invoke(); // will print "Hello"
</pre>
<p>
Function types can be used as types of arguments:
</p>
<pre class="displaycode">
static void doTwice({ => void } block) {
block.invoke();
block.invoke();
}
public static void main(String[] args) {
doTwice({ => System.out.println("deja vu"); });
}
</pre>
<p>
They can also serve as a return type:
</p>
<pre class="displaycode">
static { => boolean } makeCond() {
return { => Math.random() < 0.8 };
}
public static void main(String[] args) {
{ => boolean } cond = makeCond();
while (cond.invoke()) {
System.out.println("trying...");
}
}
</pre>
<hr/>
<h2>Exercises</h2>
<ol>
<li>Write a method that invokes an action on each value of array of ints. The action is passed in a function variable.</li>
<li>Write a method that returns a closure which checks if a value is from a given interval. Bounds of the interval
are arguments of the method.</li>
<li>Write a method that selects values from a list in accordance with a predicate passed in a function variable.</li>
</ol>
<h2>Solutions</h2>
<pre class="displaycode">
static void perform(int[] values, { int => void } action) {
for (int n: values) {
action.invoke(n);
}
}
public static void main(String[] args) {
int[] v = { 2, 3, 5, 7, 11 };
perform(v, { int x => System.out.println(x); });
}
</pre>
<pre class="displaycode">
static { int => boolean } makeInterval(int a, int b) {
return { int x => a <= x && x <= b };
}
public static void main(String[] args) {
{ int => boolean } interval = makeInterval(10, 20);
System.out.println(interval.invoke(15));
}
</pre>
<pre class="displaycode">
static <T> List<T> select(List<T> values, { T => boolean } cond) {
List<T> selected = new ArrayList<T>();
for (T t: values) {
if (cond.invoke(t)) { selected.add(t); }
}
return selected;
}
public static void main(String[] args) {
List<String> cities =
Arrays.asList("London", "New York", "Prague", "San Francisco");
List<String> shortCities =
select(cities, { String s => s.length() <= 6 });
System.out.println(shortCities);
}
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com10tag:blogger.com,1999:blog-6173836134826281546.post-73933386164675473182007-12-28T10:02:00.000-08:002008-02-28T10:55:28.287-08:00Closures<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Closures</h1>
<p>
A <i>closure</i> is a form of anonymous function. It is declared using the following syntax:<br/>
{ <i>formal parameters</i> => <i>statements</i> <i>expression</i> }. Formal parameters, statements,
and expression are optional in this clause. For example, <code>{ int x => x + 1 }</code> is
a function that takes a single int argument and returns its value incremented by 1. A closure can be invoked
by the <i>invoke</i> method. For example, <code>{ int x => x + 1 }.invoke(10)</code> will call the closure with argument 10.
</p>
<pre class="displaycode">
public class SimpleClosure {
public static void main(String[] args) {
// function with no arguments; return value is always 42
int answer = { => 42 }.invoke();
System.out.println(answer);
}
}
</pre>
<p>
A closure with one argument:
</p>
<pre class="displaycode">
double log = { double x => Math.log(x) }.invoke(10);
</pre>
<p>
A closure with a statement:
</p>
<pre class="displaycode">
// this will print "31 is odd" and return 15
int half = {
int x =>
if (x % 2 != 0) System.out.printf("%d is odd%n", x); x / 2
}.invoke(31);
</pre>
<p>
A closure with two arguments:
</p>
<pre class="displaycode">
int sum = { int x, int y => x + y }.invoke(3, 4); // will return 7
</pre>
<p>
A closure does not have to return any value (the function may have return type void):
</p>
<pre class="displaycode">
{ char c => System.out.println(c); }.invoke('@'); // will print @
</pre>
<p>
A closure that returns a string:
</p>
<pre class="displaycode">
String reversed = {
String s =>
new StringBuilder(s).reverse().toString()
}.invoke("abcd"); // will return "dcba"
</pre>
<p>
A closure that returns an instance of Runnable.
</p>
<pre class="displaycode">
{ => new Runnable() {
public void run() {
System.out.println("hi from Prague");
}
}
}.invoke().run(); // invoke() returns an instance of Runnable and we
// call run() on it immediately
</pre>
<p>
We can declare local variables in closures:
</p>
<pre class="displaycode">
{ int n =>
int m = n + 1; System.out.println(m * m);
}.invoke(3); // will print 16
</pre>
<hr/>
<h1>Implementation issue</h1>
<p>
<i>This paragraph describes how the prototype compiler implements closures.</i>
</p>
<p>
For each closure, the compiler will generate an interface with single method <code>invoke()</code>.
E.g., for closure <code>{ => 42 }</code>, the interface will look like:
</p>
<pre class="displaycode">
public interface I {
int invoke(); // no arguments and return type int
}
</pre>
<p>
And for closure { int x, int y => x + y }, the interface will be like:
</p>
<pre class="displaycode">
public interface III {
int invoke(int x, int y); // two int arguments and return type int
}
</pre>
<p>
The interface will be in the <code>javax.lang.function</code> package. Then the compiler will generate an anonymous
subclass of this interface, create an instance of this subclass, and call the invoke method.
For example, the code
</p>
<pre class="displaycode">
public static void main(String[] args) {
int answer = { => 42 }.invoke();
System.out.println(answer);
}
</pre>
<p>
will be tranformed approximately as follows:
</p>
<pre class="displaycode">
public static void main(String[] args) {
int answer = new javax.lang.function.I() {
public int invoke() {
return 42;
}
}.invoke();
System.out.println(answer);
}
</pre>
<p>
So, at runtime a closure is represented as object. In JSR, this object is called the <i>closure object</i>.
</p>
<hr/>
<h2>Exercises</h2>
<ol>
<li>Write a closure that returns the lesser of two double values.</li>
<li>Write a closure that decides if a value is even.</li>
<li>Write a closure that returns last n characters of a string.</li>
</ol>
<h2>Solutions</h2>
<pre class="displaycode">
double min1 = { double x, double y => x < y ? x : y }.invoke(7.5, 8.2);
double min2 = {
double x, double y =>
double m; if (x < y) m = x; else m = y; m
}.invoke(10.22, 9.76);
</pre>
<pre class="displaycode">
boolean even = { int x => x % 2 == 0 }.invoke(15);
</pre>
<pre class="displaycode">
{ String, int => String } lastNChars =
{ String s, int n => int len = s.length(); s.substring(len - n, len) };
</pre>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com38tag:blogger.com,1999:blog-6173836134826281546.post-81441440397628175132007-12-28T10:00:00.000-08:002008-11-14T00:52:56.341-08:00Java Closures Tutorial<script language="JavaScript" src="http://www.gvisit.com/record.php?sid=72234ddeabfba31b7488cbf00de3989c" type="text/javascript"></script>
<h1>Java Closures Tutorial</h1>
<p><b>JSR Proposal: Closures for Java, section 2:</b></p>
<p>
'This JSR provides support for operating on an arbitrary "block of Java code", or body, which is either a statement list,
an expression, or a combination of both. We call the mechanism a closure expression. Wrapping statements or an expression in
a closure expression does not change their meaning, but merely defers their execution. Evaluating a closure expression
produces a closure object. The closure object can later be invoked, which results in execution of the body, yielding the value
of the expression (if one was present) to the invoker. A closure expression can have parameters, which act as variables whose
scope is the body. In this case the invoker of the closure object must provide compatible arguments, which become the values
for the parameters.'
</p>
<p>
This tutorial does <i>not</i> describe the whole proposal but only the features implemented in the prototype compiler. All examples in this tutorial were tested against the early prototype available at <a href="http://www.javac.info/">http://www.javac.info</a>.
Current version:
<a href="http://www.javac.info/closures.tar.gz">closures.tar.gz</a>
</p>Zdeněk Troníčekhttp://www.blogger.com/profile/12818559511505042249noreply@blogger.com249