0

I am tinkering around with Kotlin and I am trying to wrap my head around how nullable variables work in Kotlin. Here I have a piece of code that does a boolean check to see if a vehicle is over capacity. Is the implementation a good way to work with nullable variables or is there a more elegant way ?

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
    }
}

Thanks a lot!

k88
  • 1,858
  • 2
  • 12
  • 33

2 Answers2

5
fun isOverCapacity(): Boolean {
    val vehicleCapacity = vehicle?.capacity ?: return false
    val totalDemand = jobs?.sumBy { job -> job.demand } ?: return false
    return totalDemand > vehicleCapacity
}

What does ?: do in Kotlin? (Elvis Operator)

IR42
  • 8,587
  • 2
  • 23
  • 34
1

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.

  • let -> returns the result of lambda expression.
  • run -> returns the result of lambda expression passing this as receiver.
  • also -> does operation and returns itself unlike the result of lambda.
  • apply -> does operation and returns itself unlike the result of lambda passing this as receiver.
  • use -> returns the result of lambda expression and closes the Closeable resource.

You can simplify the code as follows:

fun isOverCapacity() : Boolean =
    vehicle?.capacity?.let { vehicleCapacity ->
        jobs?.sumBy { job -> job.demand }?.let { totalDemand ->
            totalDemand > vehicleCapacity
        }
    } ?: false
Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49