This code attempts to calculate the total price of items in a shopping cart. What is the potential null-safety issue and how can it be fixed?

Android interview question for Advanced practice.

Answer

The code might produce unexpected results because sumOf will ignore null values, potentially undercounting the total.

Explanation

While the Elvis operator (?:) prevents a NullPointerException, it silently substitutes a 0.0 for null prices. This means that items with null prices effectively contribute nothing to the total, resulting in an undercount. The sumOf function ignores null values in this context. To fix this, you should either filter out items with null prices or handle them appropriately. Here's a corrected version that handles null prices by using a custom calculation: kotlin val totalPrice = cart.sumOf { it.price?.toDouble() ?: 0.0 } This version uses the safe-call operator to safely access price and convert it to Double, while ensuring any null prices are treated as 0.0. Alternatively, you could filter out the null prices before summation: kotlin val totalPrice = cart.filter { it.price != null }.sumOf { it.price!! } This filters out items with null prices before using the sumOf function, but introduces the !! operator, so the first approach might be preferable for clarity and safety.

Related Questions