Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"AssignmentOperator Expression" error on simple lambda expression code

Tags:

java

lambda

I'm learning how to use lambda expressions now, and I've seen some tutorials with a simple example:

(int x) -> x + 5;

But my compiler is showing this error:

Syntax error, insert "AssignmentOperator Expression" to complete Expression

Am I forgetting something?

like image 220
Mateus Avatar asked Dec 07 '22 20:12

Mateus


1 Answers

Lambda expressions always have to be assigned to a reference type of Functional Interafces (also called single abstract method interfaces). Infact, they provide shortcut to the verbose anonymous class (with single method) implementations.

So, in simple words, Lambda expression = abstract method implementation (of the functional interface).

For example, your expression can be assigned to the below Functional Interface:

public interface MyInterface {//define Functional Interafce (SAM)
    public int someMethod(int a);
}

public class Test {
   public static void main(String[] args) {
        MyInterface myInterface = (int a) -> a +5;//assign the expression to SAM
        int output = myInterface.someMethod(20)); //returns 25
   }
}
like image 110
developer Avatar answered Mar 21 '23 19:03

developer