rayman
rayman

Reputation: 21596

How to use generic param with Lambdas

Assume we have the following code without Lambdas:

doSomething.consumer("someString", new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    //do some code                         
                }
            });

How could I convert this code using Lambdas and using the Lambda's param as

 Handler<Message<JsonObject>>

This is what the consumer method looks like:

<T> MessageConsumer<T> consumer(String address, Handler<Message<T>> handler);

Upvotes: 2

Views: 95

Answers (3)

Smutje
Smutje

Reputation: 18123

Do you want to re-write the handler using lambda's? Could be something like the following

<T> MessageConsumer<T> consumer(String address, Function<Message<T>, Void> function);

and instead of

doSomething.consumer("someString", new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> event) {
                //do some code                         
            }
        });

you could write

doSomething.consumer("someString", message -> null);

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can do this to define what T is

doSomething.<JsonObject>consumer("someString", event -> { /* do some code */ });

or define what type event is

doSomething.consumer("someString", (Message<JsonObject> event) -> { /* do some code */ });

or define what type you expect the Handler to be.

doSomething.consumer("someString", (Handler<Message<JsonObject>>) 
                                   (event -> { /* do some code */ }));

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691715

MessageConsumer<JsonObject> consumer = 
    doSomething.consumer("someString", event -> {
        // some code
    });

Upvotes: 0

Related Questions