kotlin - Kotlin:类型推断失败。预期的类型不匹配:推断的类型为Pair <String,Int>,但希望Pair <Product,Int>

标签 kotlin

我想调用主要运行以下函数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/

相关文章:

java - Spring Boot : Adding @Transactional produces java. lang.ClassNotFoundException : org.spectj.util.PartialOrder$PartialComparable

Kotlin 中的 Java Boolean.valueOf() 等价物?

inheritance - 在 Kotlin 中扩展 Java 类时继承的平台声明冲突

java - Fragment和Activity之间的通信

kotlin - Jetpack 撰写 : Notify changes in StateFlow

android - 自定义导航图标不显示//Jetpack Navigation

gradle - Kotlin 的 gradle kapt 插件不适用于自定义源集 (JMH)

java - Android:以画中画模式播放视频(点击关闭按钮时多次出现)

android - Firebase Crashlytics 使用 Retrofit 和协程报告 Android 项目上的假崩溃

android - 使用消息 "method not allowed here"改造响应代码 405