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!

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.