欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java与Scala中的闭包 博客分类: 函数式语言 JavaScalajava7SQLJDK 

程序员文章站 2024-02-16 18:19:16
...
  原文地址Closures in Java and Scala
  翻  译Eastsun


  People argue that verbose code is easier to understand. Do you agree when reading these two examples, one method in Java, one in Scala?
  人们普遍认为,详细的代码更易于理解。但如果你阅读下面两段代码--一个使用Java另一个使用Scala--你是否还这样认为呢?
public List<Item> bought(User user) {
    List<Item> result = new ArrayList();
    for (Item item : currentItems) {
        if (user.bought(item)) {
            result.add(item);
        }
    }
    return result;
}

def bought(user: User) = items.filter(user bought _)


  If you are familiar with Java, which is more likely then you being familiar with Scala, you may tend to the Java-version. Scala has a different syntax for declaring types and generics, and supports closures, including anonymous parameters (the underscore).
  如果你熟悉Java,那么很可能你将会了解到Scala。也许你会倾向于使用Java的版本。Scala具有不同的类型声明以及泛型语法,并且支持闭包,以及匿名参数(下划线)。

  When Closures are introduced in one of the next Java releases, JDK 7 or 8, the example could be rewritten like this:
  在Java的后续版本中引入闭包后(JDK7或JDK8),上面Java版的代码可以重写为:
public List<Item> bought(User user) {   
    return ListUtils.filter(Item item : items ) {      
        user.bought(item);    
    }
}

  Or with extension methods:
  或者使用方法扩展
public List<Item> bought(User user) { 
    return items.filter(Item item : )  { 
        // <-- note the smily! thats what its all about!
        user.bought(item);
    }
}

  The interesting differences between Java with closures and Scala is the static typing: Scala inferences that items are all of type Item, so there is no need to specify that information again.

  带有闭包的Java与Scala一个让人感兴趣的区别是它们的静态类型:Scala的类型推断能力能得到其所有变量的类型,因此不需要再指明这一点。

  So, while the current Java Closures specification is a great step in the right direction, lead by Neil Gafter, who is quite the right man for the job, it may not be worth to wait for it, if you have the choice. Its not even sure yet that we'll see that spec implemented in JDK7, and even that is at best one and a half year away.
  因此,即便目前的JAVA闭包规范Neil Gafter的领导下正朝着正确的方向做出了很大的进步;但我们也未必需要去等待它,如果我们已经有了其他选择。何况JDK7中会不会实现闭包现在还没有确定--即便是,那也至少是一年半以后的事了。