如何使用谓词在Kotlin中过滤
我要实现的目标是使用具有动态谓词的过滤器函数。 到目前为止,我所做的是创建一个选择最佳谓词的函数:
fun buildDatePredicate(dateFrom: LocalDate?, dateTo: LocalDate?): Predicate<MyClass> {
if (dateFrom != null && dateTo == null) {
return Predicate { myItem -> myItem.date.isAfter(dateFrom) }
}
if (dateTo != null && dateFrom == null) {
return Predicate { myItem -> myItem.date.isBefore(dateTo) }
}
if (dateTo != null && dateFrom != null) {
return Predicate { myItem ->
myItem.date.isBefore(dateTo) && myItem.date.isAfter(dateFrom)
}
}
return Predicate { true }
}
然后我尝试使用该谓词在列表上使用过滤器,
myList.filter { buildDatePredicate(fromDate.toLocalDate(),toDate.toLocalDate()) }
但它无法正常工作
Type mismatch.
Required:
Boolean
Found:
Predicate<MyClass>
但是由于可以实现我要做的事情,
?谢谢
What i'm trying to achieve is using a filter function with dynamic predicates.
What I did so far is creating a function that choose the best predicate:
fun buildDatePredicate(dateFrom: LocalDate?, dateTo: LocalDate?): Predicate<MyClass> {
if (dateFrom != null && dateTo == null) {
return Predicate { myItem -> myItem.date.isAfter(dateFrom) }
}
if (dateTo != null && dateFrom == null) {
return Predicate { myItem -> myItem.date.isBefore(dateTo) }
}
if (dateTo != null && dateFrom != null) {
return Predicate { myItem ->
myItem.date.isBefore(dateTo) && myItem.date.isAfter(dateFrom)
}
}
return Predicate { true }
}
And then I tried to use filter on my list using that Predicate
myList.filter { buildDatePredicate(fromDate.toLocalDate(),toDate.toLocalDate()) }
But it does not works due to
Type mismatch.
Required:
Boolean
Found:
Predicate<MyClass>
Is it possible to achieve what i'm trying to do?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个简单的解决方案是在谓词上只调用
test
-Method:但是Kotlin中更惯用的解决方案是不使用
java.util.function.function.predicate.predicate
,而是类型(myClass)的函数 - &gt;布尔值
。然后,您只需将builddatePredicate
的结果直接传递到过滤器函数即可。这样:然后将其称为:
A simple solution is to just call the
test
-method on the predicate:But a more idiomatic solution in Kotlin is to not use
java.util.function.Predicate
, but rather a function of type(MyClass) -> Boolean
. Then you can just pass the result ofbuildDatePredicate
directly to the filter function. Like this:And then call it with: