Search code examples
javajavafxlambdaexpressionchangelistener

Erroneous conversion to lambda expression in Java


I currently work with JavaFx in Netbeans IDE, however Eclipse behaves probably the same. When I use for-loop it usually offends me to convert the statement to lambda expression. Sometime I find it useful until it gives the erroneous expression.

I try to apply the conversion tool to the event, when the selected item in a ComboBox is changed:

command.valueProperty().addListener(new ChangeListener<String>() {
    @Override 
    public void changed(ObservableValue ov, String t, String t1) {                
        System.out.println(t1);              
    }    
});

The conversion results in:

command.valueProperty().addListener((ObservableValue ov, String t, String t1) -> {
    System.out.println(t1);    
});

that looks a bit nicer, however is erroneous:

no suitable method found for addListener((Observabl[...]1); })

When I keep the original code, it works like a charm. Why my IDE offers me a not correct conversion? How to fix the functional method to work well?


Solution

  • Edit

    I just tried your example on IntelliJ (sorry, I don't have NetBeans installed) and it generates the proper code and runs fine:

    new ChoiceBox<String>()
        .valueProperty()
        .addListener((ov, t, t1) -> System.out.println(t1));
    

    Your original code is incomplete, ObservableValue needs a type parameter, i.e.: ObservableValue<? extends String>. If you do not provide one, the compiler is unable to infer the correct type