How to convert this code to java8 lambda

后端 未结 3 1761
暖寄归人
暖寄归人 2021-01-13 15:04

I\'ve just started working with Java 8 and I\'m struggling with this code snippet:

paramsValues[idx++] = new ReplyMessage() {
    @Override         


        
相关标签:
3条回答
  • 2021-01-13 15:08

    Lambda expressions are only possible with Functional Interfaces (Interfaces with only one method, such as Runnable or ActionEvent)

    If ReplyMessage is a functional interface, you can do:

    paramsValues[idx++] = reply -> message.reply(reply);
    

    Lambda expressions are formed in this pattern: parameters that the method should take, then -> then the method body

    Here is the code of how ReplyMessage interface should look like:

    @FunctionalInterface
    interface ReplyMessage<T> {
        void reply(T jo);
    }
    

    For more information, consider reading this.

    0 讨论(0)
  • 2021-01-13 15:15
    paramValues[idx++] = reply -> message.reply(reply);
    

    Or

    paramValues[idx++] = reply -> {
        return message.reply(reply);
    }
    

    It will work as long as ReplyMessage<JsonObject> is functional interface and paramValues is of type ReplyMessage<JsonObject>.

    0 讨论(0)
  • 2021-01-13 15:29

    If ReplyMessage is a functional interface, you could do

    paramsValues[idx++] = reply -> message.reply(reply);
    

    Here's a full example with stub implementations of the other classes in your question:

    // Stub classes
    class JsonObject { }
    
    @FunctionalInterface
    interface ReplyMessage<T> {
        void reply(T jo);
    }
    
    class LambdaDemo {
        public static void main(String args[]) {
    
            // Dummy variables
            ReplyMessage<JsonObject> message = new ReplyMessage<JsonObject>() {
                public void reply(JsonObject jo) {}
            };
            ReplyMessage[] paramsValues = new ReplyMessage[5];
            int idx = 0;
    
            // Your code, lambdafied
            paramsValues[idx++] = reply -> message.reply(reply);
    
            // Or,
            // paramsValues[idx++] = message::reply;
    
            // But then you could perhaps do with just ...
            // paramsValues[idx++] = message;
        }
    }
    
    0 讨论(0)
提交回复
热议问题