代码目的: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)
谢谢!
如果要在实例化对象时运行 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类,类型参数T和U是不必要的,因为您不会在任何地方使用它们,并且类本身是由标准库提供的(标头看起来像data class Pair<out A, out B>(val first: A, val second: B).
如果您决定使用自己的 Pair 类,请确保将其设为 a data class,以便对其进行解构,并将其类型更改productAndQuantityList为mutableListOf<Pair>(不带类型参数Pair<Product, Int>)。
请阅读 Mathias Henze 的答案,这是正确的。我的回答,原本是完全错误的,但我现在已经更正了。
| 归档时间: |
|
| 查看次数: |
1276 次 |
| 最近记录: |