Method Closures

You may have read the latest closure proposal for Java (Nominal Closures for Java (version 0.2)).

A simple example given in Neal Gafter's page is as follows:

interface IntFunction {
   int invoke(int i);
}
IntFunction plus2 = (int x){ x+2 };

Essentially, closures types exists transiently only at compile time - closure types are converted at object types at compile time. [Note: I wonder why user has to repeat the types of closure parameters - why not allow (x) { x + 2 }; and infer the "x"'s type to be int from the IntFunction.invoke's signature. In fact, it seems that the return type of closure is inferred rather than specified. Am I missing something??]

Groovy supports closures. Also, it supports method closures.


class Person {
  def name
  Person(name) {
    this.name = name
  }

  def greet() {
    println "Hello, I'm ${name}"
  }
}

p = new Person("Sundar")
// The ".&" operator converts a method as Closure
greet = p.&greet
// the following prints true
println(greet instanceof Closure)
// call the method closure 
greet()

For Groovy, there are these is an RFE to allow conversion from closure to interface. For now, user can use the following with Groovy JSR-223 engine.


import java.awt.\*;
import java.awt.event.\*;

class Person {
  def name
  Person(name) {
    this.name = name
  }

  def greet(ActionEvent evt) {
    println "Hello, I'm ${name}"
  }
}


p = new Person("Sundar");
// just assign method closure to
// a global variable - the name of
// the variable matches interface
// method we want to implement
actionPerformed = p.&greet;

f = new Frame("hello")
b = new Button("greet")
f.add(b, "Center")

// Note: "engine" is a variable of type javax.script.ScriptEngine
b.addActionListener(engine.getInterface(ActionListener));
f.setVisible(true);

You might think that I could perhaps implement ActionListener directly by Person class. But, the assumption is that Person class could be from a third party library which you can't (or don't want to) modify. And you want to avoid writing wrappers. That is when method closures along with interface conversion can help.

Method closures could be added to Java as well (see also: better closures)


interface IntFunction {
 int invoke(int i);
}

Person p = new Person();

// closure conversion of a method closure
IntFunction func = p.&greet; 

Comments:

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder