Kotlin:函数声明必须有一个名称

use*_*983 3 kotlin

代码目的:Class Pair 可以打印出产品名称和数量,产品名称存储在Class Product

class Pair<T, U>(var product: Product, var quantity: Int) {
    for ( (product,quantity) in productAndQuantityList) {
        println("Name: ${product.productName}")
        println("Quantity: $quantity")
    }
}
Run Code Online (Sandbox Code Playgroud)

以上错误:(2, 9) Kotlin:期望成员声明错误:(2, 57) Kotlin:函数声明必须有一个名称

class ShoppingCart{
    private val productAndQuantityList = mutableListOf<Pair<Product,Int> >()
...
}

open class Product(
    val productName: String,
    var basePrice: Double,
    open val salesPrice: Double,
    val description: String) {
...}
Run Code Online (Sandbox Code Playgroud)
  1. 我可以知道如何更改我的代码吗?
  2. 在 Compiler 建议使用类 Pair 之后,但我应该填写任何内容吗?
  3. 我应该为哪个主题工作,以避免再次出现相同的错误?

谢谢!

use*_*ser 5

如果要在实例化对象时运行 for 循环,则应使用初始化程序。您不能简单地将语句直接放在类定义中。

class Pair<T, U>(var product: Product, var quantity: Int) {
  init {
    for ( (product,quantity) in productAndQuantityList) {
        println("Name: ${product.productName}")
        println("Quantity: $quantity")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,此代码是错误的,因为尽管Pair可以访问productAndQuantityList,但无法访问ShoppingCart。正如 Mathias Henze 建议的那样,您应该在其中创建一个函数ShoppingCart并将 for 循环移动到其中,如下所示:

fun printProducts() {
  for ( (product,quantity) in productAndQuantityList) {
    println("Name: ${product.productName}")
    println("Quantity: $quantity")
  }
}
Run Code Online (Sandbox Code Playgroud)

至于您的Pair类,类型参数TU是不必要的,因为您不会在任何地方使用它们,并且类本身是由标准库提供的(标头看起来像data class Pair<out A, out B>(val first: A, val second: B).

如果您决定使用自己的 Pair 类,请确保将其设为 a data class,以便对其进行解构,并将其类型更改productAndQuantityListmutableListOf<Pair>(不带类型参数Pair<Product, Int>)。

更新

请阅读 Mathias Henze 的答案,这是正确的。我的回答,原本是完全错误的,但我现在已经更正了。