0

Kotlin Shipping calculator task

Hi everyone! Could please someone explain to me why the hell it is constantly demanding to "initialize "total" variable"? fun shippingCost(amount: Double, international: Boolean, total: Double): Double { var total: Double if (international == true) { if ((amount * 0.15) > 50.0) { return (total) } else { total = amount * 0.15 } return (total) } else if (international == false) { if (amount < 75.0) { total = amount * 0.10 } else { total = 0.0 } } return (total) } fun main(args: Array<String>) { var amount = 140.0 val total = readLine()!!.toDouble() val international = readLine()!!.toBoolean() println(shippingCost(total, international)) }

24th Apr 2022, 7:23 PM
Olesia
4 Antworten
+ 3
You can return an expression, or a constant value also. For example these are valid, and might work if you use them in the correct place. return 50.0 return amount * 0.15 return 0.0 You don't really need to declare new variable in the function, because the calculation is very simple. Read the instruction very carefully, to understand which condition results in which amount.
24th Apr 2022, 7:48 PM
Tibor Santa
Tibor Santa - avatar
+ 1
The task: You are working on a eCommerce website and need to make a shipping cost calculator based on the order amount. The store uses the following cost structure: For orders in the US: - $75+ orders have free shipping - orders less than $75 have a shipping fee of 10% of the total order amount. For international orders, there is a 15% shipping fee, with a maximum of $50. This means that the maximum shipping fee for an international order is $50. You need to complete the given shippingCost() function, which takes the order amount and a Boolean indicating whether the order is international or not, and returns the shipping cost for that order. The return amount should be a Double.
24th Apr 2022, 7:26 PM
Olesia
+ 1
After you define total, as a local scoped variable within the shippingCost function, your program may immediately return it in the next if statement, without giving it any value. This is illegal in Kotlin, the compiler warns you that total has not been initialized (= given a value). Double type cannot be null. Actually, your function signatures are also inconsistent. And if you use 'total' as a parameter, you should not use the same name for a new variable inside the function, that is very confusing.
24th Apr 2022, 7:34 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa thank you! Reg. Total as a parameter - agree, deleted it from the function arguments. But if I delete this variable, what shall i specify in "return"?
24th Apr 2022, 7:37 PM
Olesia