What does "->" mean in Java?
I am studying this tutorial. Some screenshots have the ->
construction, for example:
vertx.deployVerticle("com.mycompany.MyOrderProcessorVerticle", res -> {
if (res.succeeded()) {
System.out.println("Deployment id is: " + res.result());
} else {
System.out.println("Deployment failed!");
}
});
I've never encountered this before. Please tell me what it is and where you can read good materials about it.
1 answers
This lambda expression is an anonymous function. Simply put, it is a method without declaring (without access modifiers that return a value and a name).
Appeared in version 8 of Java.
Usage example
Let's write a simple example of the functional interface :
public interface Lambda {
//Метод интерфейса с отсутсвующей реализацией
int getDoubleValue(int val);
//Метод интерфейса с реализацией по-умолчанию
default void printVal(int val) {
System.out.println(val);
}
}
A functional interface must have only one abstract method. You can read about the reasons for this restriction here.
Now let's create a class to use
public class ClassForLambda {
public static void main(String[] args) {
//Объявляем ссылку на функциональный интерфейс
Lambda lam;
//Параметр для нашего абстрактногго метода
int num =9;
//Прописываем первый вариант реализации
lam = (val) -> val * 2;
System.out.println(lam.getDoubleValue(num));
//Прописываем второй вариант реализации
lam = (val) -> {
System.out.println("Your number is "+val);
return val * 2;
};
System.out.println(lam.getDoubleValue(num));
}
}
As you can see, the reference to the method has not changed. Only the implementation was changed.