Home  >  Article  >  Java  >  Lambda expression syntax description in java

Lambda expression syntax description in java

高洛峰
高洛峰Original
2017-01-23 15:42:101600browse

Syntax Description

A lambda expression consists of the following parts:

1. A comma-separated list of formal parameters in parentheses. The CheckPerson.test method contains a parameter p, which represents an instance of the Person class. Note: The type of the parameter in the lambda expression can be omitted; in addition, if there is only one parameter, even the parentheses can be omitted. For example, the code mentioned in the previous section:

p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
    && p.getAge() <= 25

2. Arrow symbol: ->. Used to separate parameters and function bodies.

3. Function body. Consists of an expression or block of code. In the example in the previous section, such an expression was used:

   
p.getGender() == Person.Sex.MALE
      && p.getAge() >= 18
      && p.getAge() <= 25

If an expression is used, the Java runtime will calculate and return the value of the expression. In addition, you can also choose to use the return statement in the code block:

p -> {
  return p.getGender() == Person.Sex.MALE
      && p.getAge() >= 18
      && p.getAge() <= 25;
}

However, the return statement is not an expression. In lambda expressions, statements need to be enclosed in curly braces. However, there is no need to enclose statements in curly braces when just calling a method that returns a null value, so the following writing is also correct:

email -> System.out.println(email)

lambda expressions and method declarations look a lot alike. Therefore, lambda expressions can also be regarded as anonymous methods, that is, methods without defined names.

The lambda expressions mentioned above are all expressions that use only one parameter as a formal parameter. The following instance class, Caulator, demonstrates how to use multiple parameters as formal parameters:

package com.zhyea.zytools;
 
public class Calculator {
 
  interface IntegerMath {
    int operation(int a, int b);
  }
 
  public int operateBinary(int a, int b, IntegerMath op) {
    return op.operation(a, b);
  }
 
  public static void main(String... args) {
    Calculator myApp = new Calculator();
    IntegerMath addition = (a, b) -> a + b;
    IntegerMath subtraction = (a, b) -> a - b;
    System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition));
    System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction));
  }
}

The operateBinary method in the code uses two integer parameters to perform arithmetic operations. The arithmetic operation here itself is an instance of the IntegerMath interface. In the above program, two arithmetic operations are defined using lambda expressions: addition and subtraction. The execution program will print the following content:

40 + 2 = 42
20 - 10 = 10

Accessing local variables of external classes

Similar to local classes or anonymous classes, lambda expressions can also access local variables of external classes. The difference is that there is no need to consider issues such as overwriting when using lambda expressions. A lambda expression is just a lexical concept, which means it does not need to inherit any name from a superclass, nor does it introduce new scope. That is, a declaration within a lambda expression has the same meaning as a declaration in its external environment. This is demonstrated in the following example:

package com.zhyea.zytools;
 
import java.util.function.Consumer;
 
public class LambdaScopeTest {
 
  public int x = 0;
 
  class FirstLevel {
 
    public int x = 1;
 
    void methodInFirstLevel(int x) {
      //如下的语句会导致编译器在statement A处报错“local variables referenced from a lambda expression must be final or effectively final”
      // x = 99;
      Consumer myConsumer = (y) ->{
        System.out.println("x = " + x); // Statement A
        System.out.println("y = " + y);
        System.out.println("this.x = " + this.x);
        System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x);
      };
 
      myConsumer.accept(x);
    }
  }
 
  public static void main(String... args) {
    LambdaScopeTest st = new LambdaScopeTest();
    LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
    fl.methodInFirstLevel(23);
  }
}


This code will output the following:

   
x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0


If the parameter y in the lambda expression myConsumer in the example is replaced with x, the compiler will report an error:

Consumer myConsumer = (x) ->{
      // ....
    };


The compiler error message is : "variable x is already defined in method methodInFirstLevel(int)", which means that variable x has been defined in method methodInFirstLevel. The error is reported because lambda expressions do not introduce new scopes. Therefore, you can directly access the field fields, methods and formal parameters of the external class in lambda expressions. In this example, the lambda expression myConsumer directly accesses the formal parameter x of the method methodInFirstLevel. When accessing members of external classes, you also use the this keyword directly. In this example this.x refers to FirstLevel.x.

However, like local classes or anonymous classes, lambda expressions can only access local variables or external members that are declared final (or equivalent to final). For example, we remove the comment before "x=99" ​​in the methodInFirstLevel method in the sample code:

//如下的语句会导致编译器在statement A处报错“local variables referenced from a lambda expression must be final or effectively final”
x = 99;
Consumer myConsumer = (y) ->{
  System.out.println("x = " + x); // Statement A
  System.out.println("y = " + y);
  System.out.println("this.x = " + this.x);
  System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x);
};


Because the value of parameter x is modified in this statement, methodInFirstLevel The parameter x can no longer be considered final. Therefore, the Java compiler will report an error like "local variables referenced from a lambda expression must be final or effectively final" where the lambda expression accesses the local variable x.

Target type

How to determine the type of lambda expression. Let’s take a look at the code for screening military service-age personnel:

   
p -> p.getGender() == Person.Sex.MALE
       && p.getAge() >= 18
       && p.getAge() <= 25


This code has been used in two places:

public static void printPersons(List1a25c849577936f4023e1039b288606e roster, CheckPerson tester) - Option 3
public void printPersonsWithPredicate(List8abf60ac54173a2785e603c7a1f95b4e roster, Predicate8abf60ac54173a2785e603c7a1f95b4e tester) —— Option 6

When calling the printPersons method, this The method expects a parameter of type CheckPerson, and the above expression is an expression of type CheckPerson. When calling the printPersonsWithPredicate method, a parameter of type Predicate8abf60ac54173a2785e603c7a1f95b4e is expected, and the same expression is of type Predicate8abf60ac54173a2785e603c7a1f95b4e. Like this, the type determined by the type expected by the method is called the target type (in fact, I think the type inference in Scala is more suitable here). The Java compiler determines the type of a lambda expression through the context of the target type or the position where the lambda expression is found. This means that lambda expressions can only be used where the Java compiler can infer the type:

Variable declaration;

Assignment;

Return statement;

Array initialization;

Method or constructor parameters;

lambda expression method body;

Conditional expression (?:);

When an exception is thrown.

Target type and method parameters

对于方法参数,Java编译器还需要依赖两个语言特性来决定目标类型:重载解析和类型参数推断。

看一下下面的这两个函数式接口( java.lang.Runnable and java.util.concurrent.Callabled94943c0b4933ad8cac500132f64757f):

public interface Runnable {
    void run();
  }
 
  public interface Callable {
    V call();
  }


Runnable.run()方法没有返回值,而Callable.call()方法有。

假设我们像下面这样重载了invoke方法:

void invoke(Runnable r) {
   r.run();
 }
 
  T invoke(Callable c) {
   return c.call();
 }


那么在下面的语句中将会调用哪个方法呢:

String s = invoke(() -> "done");

调用的是invoke(Callable8742468051c85b06f0a0af9e3e506b5c),因为这个方法有返回值,而invoke(Runnable8742468051c85b06f0a0af9e3e506b5c)没有返回值。在这种情况下lambda表达式(() -> “done”)的类型是Callable8742468051c85b06f0a0af9e3e506b5c。

序列化

如果一个lambda表达式的目标类型还有它调用的参数的类型都是可序列化的,那么lambda表达式也是可序列化的。然而就像内部类一样,强烈不建议对lambda表达式进行序列化。

更多java中lambda表达式语法说明相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn