我正在修补Kotlin,并且试图绕过Kotlin中可空变量的工作方式。在这里,我有一段代码进行布尔检查,以查看车辆是否超载。实现是使用可空变量的好方法还是有一种更优雅的方法?
class Route(var vehicle: Vehicle?, var jobs: List<Job>?) {
constructor()
constructor(vehicle: Vehicle?)
fun isOverCapacity() : Boolean {
val vehicleCapacity = vehicle?.capacity
if (vehicleCapacity != null){
val totalDemand = jobs?.sumBy { job -> job.demand }
if (totalDemand != null) {
return totalDemand > vehicleCapacity
}
}
return false
}
}
非常感谢!
By using kotlin std-lib dsl functional operators like let, run, also, apply, use.
Use of
?.
-> if the object/value is not null then only call the next function.您可以简化代码,如下所示: