Java Lambdas和Closures [英] Java Lambdas and Closures

查看:102
本文介绍了Java Lambdas和Closures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到lambdas即将到达您附近的Java(J8)。我发现一个例子,他们将在一些博客上看起来像:

I hear lambdas are coming soon to a Java near you (J8). I found an example of what they will look like on some blog:

SoccerService soccerService = (teamA, teamB) -> {
    SoccerResult result = null;
    if (teamA == teamB) {
        result = SoccerResult.DRAW;
    }
    else if(teamA < teamB) {
        result = SoccerResult.LOST;
    }
    else {
        result = SoccerResult.WON;
    }

    return result;
};

立即关闭


  • teamA teamB 在哪里输入?或者不是他们(像一些怪异的泛型)?

  • 是一个lambda类型的闭包, li>
  • 这会给我一个典型的匿名函数有什么好处?

  • Where are teamA and teamB typed? Or aren't they (like some weird form of generics)?
  • Is a lambda a type of closure, or is it the other way around?
  • What benefits will this give me over a typical anonymous function?

推荐答案

Lambda表达式只是语法糖来实现目标接口,将通过lambda表达式在接口中实现特定的方法。编译器可以推断出接口中的参数类型,这就是为什么你不需要在lambda表达式中明确定义它们的原因。

The Lambda expression is just syntactic sugar to implement a target interface, this means that you will be implementing a particular method in the interface through a lambda expression. The compiler can infer the types of the parameters in the interface and that's why you do not need to explicitly define them in the lambda expression.

例如:

Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase(s2);

在这个表达式中,lambda表达式显然实现了一个 Comparator 的字符串,因此,这意味着lambda表达式是语法糖用于实现 compare(String,String)

In this expression, the lambda expression evidently implements a Comparator of strings, therefore, this implies the lambda expression is syntactic sugar for implementing compare(String, String).

因此,编译器可以安全地假设 s1 s2 的类型是 String

Thus, the compiler can safely assume the type of s1 and s2 is String.

您的目标接口类型提供了编译器需要确定lambda参数的实际类型的所有信息。

Your target interface type provides all the information the compiler needs to determine what are the actual types of the lambda parameters.

Oracle Corportion的Java语言架构师Briant Goetz发布了JDK 8 Lambdas中的几篇文章。我相信您的问题答案如下:

Briant Goetz, Java Language Architect at Oracle Corportion has published a couple of articles of the work in progress in JDK 8 Lambdas. I believe the answers to your questions are there:

  • State of Lambda.
  • State of Lambda Libraries Edition.
  • Translation of Lambda Expressions
  • JVMLS 2012: Implementing Lambda Expressions in Java

这第二篇文章介绍了如何实现lambda表达式字节码级别,并且可以帮助您深入了解第二个问题的详细信息。

This second article explains how the lambda expressions are implemented at the bytecode level and may help you delve into the details of your second question.

这篇关于Java Lambdas和Closures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆