Search code examples
kotlinnullablesimplifysimplification

Can I combine boolean and null checks somehow? I would like to know if this kotlin method can be simplied further


I am new to Kotlin and I would like to know the most optimized way in which I can simplify the following method.

If the amount is payable by person X then I need to return the amount payable, else I need to return 0.

In the code below payments is an object that is nullable. It contains retailAmount which is also an object that's nullable. retailAmount contains baseCharges which is a Double. (Also if payments or retailAmount is null I need to return 0)

// get charges payable by X(Retailer/Shopkeeper/Customer)
fun getChargesPayableByX(personX: String): Double {
    // are charges payable by X(Retailer/Shopkeeper/Customer)?
    if (areChargesPayableByX(personX)) {  
        return payments?.retailAmount?.baseCharges ?: 0.0
    }
    return 0.0
}

Solution

  • You can do something like:

    fun getChargesPayableByX(personX: String): Double = 
        areChargesPayableByX(personX).takeIf{it == true}?.let{ payments?.retailAmount?.baseCharges } ?: 0.0