Question

We are using some socket API in Java that use extensively ActionListeners. For example:

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

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

I'd like to start simplifying part 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. Yet using the handle method is exactly what I'd like to avoid implementing.... Any idea how can I fix it ?
Thanks!

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

@FunctionalInterface

public interface SimpleFuncInterface extends  SocketHandler{

     void handle(ServerExchange exchange) throws Exception;

}

Now my code looks like this:

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

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


}

The code seems error free now, however the compiler complains that Lambda expression signature does not match the signature of the functional interface method handle(ServerExchange). Any suggestion ?

Was it helpful?

Solution

It looks like you have a syntax error in your code. Your are trying to define the lambda expression within an anonymous inner class. However, you should use the lambda expression instead of the anonymous inner class. I guess the following works:

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

If the method setHandler is overloaded, it might be necessary to provide more information, e.g. by adding a cast:

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

OTHER TIPS

with Eclipse Mars or NetBeans 8, you can do quick fix-> convert to lambda expression. (If you use java 8). kind regards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top