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

Lambda expression syntax description in java

高洛峰
Release: 2017-01-23 15:42:10
Original
1788 people have browsed it

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
Copy after login

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
Copy after login

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;
}
Copy after login

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)
Copy after login

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));
  }
}
Copy after login

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
Copy after login

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<integer> 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);
  }
}
Copy after login


This code will output the following:

   
x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0
Copy after login


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

Consumer<integer> myConsumer = (x) ->{
      // ....
    };
Copy after login


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<integer> 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);
};
Copy after login


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
Copy after login


This code has been used in two places:

public static void printPersons(List< Person> roster, CheckPerson tester) - Option 3
public void printPersonsWithPredicate(List roster, Predicate 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 Predicate is expected, and the same expression is of type Predicate. 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.Callable):

public interface Runnable {
    void run();
  }
 
  public interface Callable<v> {
    V call();
  }
Copy after login


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

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

void invoke(Runnable r) {
   r.run();
 }
 
 <t> T invoke(Callable<t> c) {
   return c.call();
 }
Copy after login


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

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

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

序列化

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template