Multiline lambda comparator
Asked Answered
C

1

13

I am starting with the lambda expressions in Java and there is something that I consider bizarre and I am sure that I am doing something wrong or it has a workaround.

To define a comparator, I can do:

 col.setComparator((CustomCell o1, CustomCell o2) ->
            ((Comparable) o1.getValue()).compareTo(o2.getValue())
        );

Which is great, however, if I just add two "{". I get a compilation error:

 col.setComparator((CustomCell o1, CustomCell o2) -> {
            ((Comparable) o1.getValue()).compareTo(o2.getValue());
        });

The error is not related to the "{", but to setComparator:

The method setComparator(Comparator<CustomCell>) in the type 
TableColumnBase<CustomParentCell,CustomCell> is not applicable for the arguments 
((CustomCell o1, CustomCell o2) -> {})

I have tried using the multiline statements before for actionevents and it does work:

 setOnAction(event -> {
        // do something
 });

Is it because it only has one argument?

Cylix answered 26/11, 2014 at 13:34 Comment(0)
D
24

The method you are implementing with setOnAction is

public void handleEvent(ActionEvent event) ;

It has a return type of void: i.e. it doesn't return anything:

The method you are implementing with setComparator is

public int compare(CustomCell cell1, CustomCell cell2) ;

which returns a value. To use the longer form, you must have an explicit return statement for methods that return a value:

col.setComparator((CustomCell o1, CustomCell o2) -> {
        return ((Comparable) o1.getValue()).compareTo(o2.getValue());
    });
Dawnedawson answered 26/11, 2014 at 13:41 Comment(1)
Thank you. Yes, that is the reason. The error I was getting was not very helpful.Cylix

© 2022 - 2024 — McMap. All rights reserved.