Reputation: 147
I wanna call run the following function addToCart() in the main, but such error appears, may i know how should i change my code? Thanks!
fun addToCart(){
println("Productname : ")
var nameInput= readLine() ?: "-"
println("Num of $nameInput ")
var num = readLine()!!.toInt()
var got : Product? = warehouse.getProductByName(nameInput)
shoppingCart.addToList(nameInput, num)
}
class ShoppingCart () {
private val productAndQuantityList = mutableListOf<Pair<Product, Int>>()
fun addToList(name: String, quantity: Int){
productAndQuantityList.add(Pair(name, quantity))
}
....
}
Upvotes: 1
Views: 1115
Reputation: 420
I think you need not null checks before calling add.
fun addProductToCart(shoppingCart: ShoppingCart, warehouse: Warehouse) {
println("Product name: ")
var productName_E = readLine() ?: "-"
println("No. of $productName_E ")
var num = readLine()?.toInt()
var got: Product? = warehouse.getProductByName(productName_E)
if (num != null && got != null) {
shoppingCart.productAndQuantityList.add(Pair(first = got, second = num))
}
}
Your ShoppingCart class should be something like the class below.
class ShoppingCart {
val productAndQuantityList = mutableListOf<kotlin.Pair<Product, Int>>()
...
}
Upvotes: 1