示例代码:
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中为真
发布评论