多线lambda比较器

时间:2014-11-26 13:34:42

标签: java lambda javafx

我开始使用Java中的lambda表达式,我认为有些事情很奇怪,我确信我做错了或者有一个解决方法。

要定义比较器,我可以这样做:

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

但是,如果我只添加两个" {"我收到编译错误:

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

错误与" {",但与setComparator无关:

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

我之前尝试过使用多行语句来执行actionevents并且确实有效:

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

是因为它只有一个参数吗?

1 个答案:

答案 0 :(得分:22)

您使用setOnAction实施的方法是

public void handleEvent(ActionEvent event) ;

它的返回类型为void:即它不会返回任何内容:

您使用setComparator实施的方法是

public int compare(CustomCell cell1, CustomCell cell2) ;

返回一个值。要使用较长的表单,必须为返回值的方法具有显式的return语句:

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