我想调用主要运行以下函数addToCart()的方法,但是会出现此类错误,请问我应该如何更改代码?
谢谢!
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))
}
....
}
最佳答案
我认为您不需要在调用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))
}
}
您的ShoppingCart类应该类似于以下类。
class ShoppingCart {
val productAndQuantityList = mutableListOf<kotlin.Pair<Product, Int>>()
...
}
关于kotlin - Kotlin:类型推断失败。预期的类型不匹配:推断的类型为Pair <String,Int>,但希望Pair <Product,Int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62006939/