k88
k88

Reputation: 1934

Boolean expression with nullable variables

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!

Upvotes: 0

Views: 178

Answers (2)

Animesh Sahu
Animesh Sahu

Reputation: 8096

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

Upvotes: 1

IR42
IR42

Reputation: 9672

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)

Upvotes: 5

Related Questions