Using a Lambda Expression in an Action Listener

We use the Java socket interface, which makes extensive use of ActionListeners. For instance:

SocketServer server = SocketFactory.create().addListener(8888, "localhost")
                .setHandler(new SocketHandler() {

                    public void handle(final ServerExchange exchange)
                            throws Exception {
                        exchange.send("Hello World");
                    }
                }).create();

I would like to start simplifying some of this code using Lambda expressions. So I started rewriting the above example using:

SocketServer server = SocketFactory.create().addListener(8888, "localhost")
            .setHandler(new SocketHandler() {
               exchange -> {
                  exchange.send("Hello World");
               }

}).create();

However, Eclipse (Luna with JDK1.8 support) complains that the method handle (..) is not implemented. However, using the descriptor method is exactly what I would like to avoid introducing .... Any idea how I can fix this?
Thank!

UPDATE: Thanks for your reply. Ok SocketHandler is an interface, however now I wrapped it in a functional interface as follows:

@FunctionalInterface

public interface SimpleFuncInterface extends  SocketHandler{

     void handle(ServerExchange exchange) throws Exception;

}

Now my code is as follows:

SocketServer  server = SocketFactory.create().addListener(8080, "localhost")
                .setHandler(doWork(() -> exchange.send("Hello World"))).create();    

        server.start();
}
private static void doWork(SimpleFuncInterface itf) {


}

, , Lambda (ServerExchange). ?

+4
2

, . . . , :

SocketServer server = SocketFactory.create().addListener(8888, "localhost")
    .setHandler(e -> { e.send("Hello World"); }).create();

setHandler , , . :

SocketServer server = SocketFactory.create().addListener(8888, "localhost")
    .setHandler((SocketHandler) e -> { e.send("Hello World"); }).create();
+7

Eclipse Mars NetBeans 8, -. ( java 8).

0

Source: https://habr.com/ru/post/1540287/


All Articles