I am quite new in Java, and I am learning Vertx recently, I can't understand how the following code works:
@Override
public void start() {
vertx.createHttpServer()
.requestHandler(req -> req.response()
.end("hello"))
.listen(8080);
}
My question is: why the parameter req
do not need to declare a type and where is this req come from?
Let's break it into pieces.
Creating instance HttpSever
using our Vertx
instance.
HttpServer httpServer = vertx.createHttpServer();
Now, for our HttpServer
we can define handler for incoming requests.
We can use for this HttpServer#requestHandler(Handler<HttpServerRequest> handler)
[1]. This method takes an instance of Handler<HttpRequest>
.
So, we can define our instance of Handler<HttpServerRequest>
as follows:
private static class MyRequestHandler implements Handler<HttpServerRequest> {
@Override
public void handle(HttpServerRequest req) {
req.response().end("Hello");
}
}
This handler will just print "Hello"
for every incoming request.
Now we can associate instance of MyReqesutHandler
with our httpServer
instance.
httpServer.requestHandler(new MyRequestHandler())
and start the HTTP server on port 8080
httpServer.listen(8080);
Note that, Handler is a so called functional interface [2] instead of defining whole class we can pass a lambda function [3] directly to httpServer.requestHandler()
.
We can avoid lots of boilerplate code.
So by using lambda we do not need to define whole class, it's enough to do:
httpServer.requestHandler(req -> req.response().end("Hello"));
Now because JAVA compiler knows the httpServer.requestHandler()
takes an instance of Handler<HttpServerRequest>
, it can infer type of req
in compile type, just by looking at method declaration.
As vert.x promotes Fluet API [4], we can chain method without need of intermediate variables.
vertx.createHttpServer()
.requestHandler(req -> req.response().end("hello"))
.listen(8080);
I strongly recommend you to look at Java lambda tutorials and get nice feeling for them, as they are used pretty much not in Vert.x only but in Java world everytwhere.
Have fun!
[2] https://www.baeldung.com/java-8-functional-interfaces
[3] https://www.geeksforgeeks.org/lambda-expressions-java-8/