开发者

Java closure introduction

开发者 https://www.devze.com 2023-03-08 17:34 出处:网络
Can any one please describe this sort of co开发者_运维知识库de to understand Java closure. public static <T> void sort(List<T> l, final {T, T=>Number} block) {

Can any one please describe this sort of co开发者_运维知识库de to understand Java closure.

public static <T> void sort(List<T> l, final {T, T=>Number} block) {

    Collections.sort(l, new Comparator<T>() {
        public int compare(T arg0, T arg1) {
            return block.invoke(arg0, arg1);
        }
    }
}


Important note: The question was regarding an earlier proposal. This was not the syntax chosen. See this Q/A as a "historical reference".


This syntax is described in the BGGA-proposal by Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahé.

This snippet of code can be described as follows:

  1. It takes as the second argument a function taking parameters (T, T) and returning Number (and assigns it to parameter block)

  2. It then creates a Comparator<T> out of it. This it does by implementing the compare method by delegating it to a call to block.

  3. Passes this comparator to the Collections.sort method.


Here comes a break down of the syntax:

public static <T> void sort(List<T> l, final {T, T=>Number} block) {
                                             ^^^^^^^^^^^^^^^^^^^^

An argument called block which is of type "function that takes two T and returns a Number".

    Collections.sort(l, new Comparator<T>() {
        public int compare(T arg0, T arg1) {
            ...
        }
    }
}

An ordinary call to Collections.sort with an instance of an anonymous subclass of Comparator as second argument...

        ...
            return block.invoke(arg0, arg1);
        ...

...which returns the number computed by the function defined by the block argument.


Put in terms of classical Java, your snippet would correspond to something like

interface Block<T> {
    public int invoke(T arg1, T arg2);
}


class Test {
    public static <T> void sort(List<T> l, final Block<T> block) {
        Collections.sort(l, new Comparator<T>() {
            public int compare(T arg0, T arg1) {
                return block.invoke(arg0, arg1);
            }
        });
    }
}


As @axtavt points out, Java 7 is (unfortunately) not going to have closures. However, Groovy does, runs on the JVM, and integrates very nicely with other Java code. I'd read this for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号