0

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
}
Devenom
  • 915
  • 1
  • 9
  • 20

1 Answers1

1

You can do something like:

fun getChargesPayableByX(personX: String): Double = 
    areChargesPayableByX(personX).takeIf{it == true}?.let{ payments?.retailAmount?.baseCharges } ?: 0.0
Saeed Entezari
  • 3,685
  • 2
  • 19
  • 40
  • 1
    Would this maybe be simpler as `payments?.retailAmount?.baseCharges.takeIf { it != null && areChargesPayableByX(personX) } ?: 0.0` ? – Yoni Gibbs Jul 16 '19 at 12:38
  • @YoniGibbs Anything that works for you. These are just different ways of writing the same thing. It does not actually optimize your code. – Saeed Entezari Jul 16 '19 at 12:51
  • @SaeedEntezari and Yoni Gibbs Thanks to your replies I just learned about the takeIf operator – Devenom Jul 17 '19 at 14:39