I study this tutorial . On some screenshots there is a 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 have not come across this before. Tell me, please, what it is and where you can read good materials about it.

  • 3
    Tynk! - Denis
  • 2
    only in Java 8 and higher - Nofate

1 answer 1

This lambda expression is an anonymous function. Simply put, this is a method without a declaration (without access modifiers that return a value and a name) .

Appeared in version 8 Java.

Usage example

Let's write a simple example of a functional interface :

 public interface Lambda { //Метод интерфейса с отсутсвующей реализацией int getDoubleValue(int val); //Метод интерфейса с реализацией по-умолчанию default void printVal(int val) { System.out.println(val); } } 

A functional interface should have only one abstract method. Read about the reasons for such a restriction here .

Now 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 call to the method has not changed. Only the implementation has changed.

References: