多线λ比较器 [英] Multiline lambda comparator
问题描述
我从Java中的lambda表达式开始,我认为有些奇怪,并且我确定自己做错了什么,或者有解决方法.
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());
});
该错误与"{"无关,但与setComparator
有关:
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) -> {})
我之前曾尝试将multiline语句用于actionevents,但它确实起作用:
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?
推荐答案
您正在使用setOnAction
实现的方法是
The method you are implementing with setOnAction
is
public void handleEvent(ActionEvent event) ;
返回类型为void
:即不返回任何内容:
It has a return type of void
: i.e. it doesn't return anything:
您正在使用setComparator
实现的方法是
The method you are implementing with setComparator
is
public int compare(CustomCell cell1, CustomCell cell2) ;
,它返回一个值.要使用更长的格式,对于返回值的方法,您必须具有显式的return语句:
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());
});
这篇关于多线λ比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!