如何检查两个布尔值?值在Kotlin中为真

编程入门 行业动态 更新时间:2024-10-05 11:14:24
本文介绍了如何检查两个布尔值?值在Kotlin中为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

示例代码:

val todayCount = keyValue.value.filter { val after = it.expectedArrivalDate?.after(today) val before = it.expectedArrivalDate?.before(tomorrow) after != null && before != null && after && before }.size

如果it.expectedArrivalDate不是nullable,我会写这样的东西:

If it.expectedArrivalDate were not nullable I would write something like that:

val todayCount = keyValue.value.filter { it.expectedArrivalDate.after(today) && it.expectedArrivalDate.before(tomorrow) }.size

是否可以简化我的代码?

Is it possible to simplify my code?

推荐答案

您可以创建扩展名功能以简化该检查.

You can create an extension functions to simplify that check.

假设expectedArrivalDate的类型为Date,则可以为可为null的日期类型Date?添加after和before函数,如果实例为null,则返回false,或者调用原始的after/before函数是否不为空:

Assuming that the type of expectedArrivalDate is Date, you could add after and before functions for the nullable Date type Date? that would return false if the instance is null, or call the original after/before functions if not null:

fun Date?.after(anotherDate: Date): Boolean = this?.after(anotherDate) ?: false fun Date?.before(anotherDate: Date): Boolean = this?.before(anotherDate) ?: false

并保持您的代码不变:

val todayCount = keyValue.value.filter { it.expectedArrivalDate.after(today) && it.expectedArrivalDate.before(tomorrow) }.size

或者您可以直接在代码中直接使用实现:

or you could just use the implementation directly in your code:

val todayCount = keyValue.value.filter { (it.expectedArrivalDate?.after(today) ?: false) && (it.expectedArrivalDate?.before(tomorrow) ?: false) }.size

更多推荐

如何检查两个布尔值?值在Kotlin中为真

本文发布于:2023-11-03 04:09:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554207.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中为   两个   布尔值   Kotlin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!