java 多行 lambda 比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27150608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:19:51  来源:igfitidea点击:

Multiline lambda comparator

javalambdajavafx

提问by luanjot

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.

我从 Java 中的 lambda 表达式开始,有一些我认为很奇怪的东西,我确信我做错了什么或者它有一个解决方法。

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:

该错误与“{”无关,而是与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:

我之前曾尝试将多行语句用于 actionevents,它确实有效:

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

Is it because it only has one argument?

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

回答by James_D

The method you are implementing with setOnActionis

您正在实施的方法setOnAction

public void handleEvent(ActionEvent event) ;

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

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

The method you are implementing with setComparatoris

您正在实施的方法setComparator

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:

它返回一个值。要使用更长的形式,您必须对返回值的方法有一个显式的 return 语句:

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