how to replace anonymous with lambda in java

前端 未结 5 989
别跟我提以往
别跟我提以往 2021-01-31 01:32

I\'ve got this code but IntelliJ tells me to replace anonymous with lambda but I don\'t know how. can anyone help me with this? Here is my code:

soundVolume.valu         


        
5条回答
  •  清酒与你
    2021-01-31 02:14

    Generally, something like that:

    methodUsingYourClass(new YourClass() {
        public void uniqueMethod(Type1 parameter1, Type2 parameter2) {
            // body of function
        }
    });
    

    is replaced with

    methodUsingYourClass((Type1 parameter1, Type2 parameter2) -> {
        // body of function
    });
    

    For your specific code:

    soundVolume.valueProperty().addListener(
           (ObservableValue ov,
                     Number old_val, Number new_val) -> {
        main.setSoundVolume(new_val.doubleValue());
        main.getMediaPlayer().setVolume(main.getSoundVolume());
    });
    

    Note the replacement of an anonymous class with lambda is possible only if the anonymous class has one method. If the anonymous class has more methods the substitution is not possible.

    From oracle documentation:

    The previous section, Anonymous Classes, shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome. Lambda expressions let you express instances of single-method classes more compactly.

提交回复
热议问题