如何检查两个布尔值?值在Kotlin中为真 [英] how to check if two Boolean? values are true in 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中为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!