【问题标题】:Kotlin: Function declaration must have a nameKotlin:函数声明必须有名称
【发布时间】:2020-05-21 20:09:06
【问题描述】:

代码目的:Class Pair可以打印出Product name和数量,Product name存放在Class Product中

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

上述错误:(2, 9) Kotlin: Expecting member declaration 错误:(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) {
...}

  1. 我可以知道如何更改我的代码吗?
  2. Compiler 建议 Pair 类之后,但我应该填写什么吗?
  3. 我应该为哪个主题工作,以避免再次出现同样的错误?

谢谢!

【问题讨论】:

  • kotlin 中已经有一个Pair 类,所以使用它,在函数中移动 for 循环代码,因为它们是可执行语句而不是声明。阅读有关方法、初始化程序等的信息。

标签: kotlin


【解决方案1】:

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

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

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

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

对于您的Pair 类,类型参数TU 是不必要的,因为您不会在任何地方使用它们,并且该类本身由标准库提供(标题类似于@ 987654331@.

如果你确定要使用自己的Pair类,一定要把它改成data class,这样就可以destructured,把productAndQuantityList的类型改成mutableListOf&lt;Pair&gt;(不带类型参数Pair&lt;Product, Int&gt;)。

更新

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

【讨论】:

  • Error:(3, 37) Kotlin: Unresolved reference: productAndQuantityList 编译器建议我创建局部变量,但“productAndQuantityList”已在类 ShoppingCart 中声明。关于如何解决它的任何想法?谢谢
  • 我相信上面@Mathias 的反馈评论现在已经过时了,因为这个答案已被大幅修改。
【解决方案2】:

productAndQuantityList 仅用于存储数据。 Pair 类是 Kotlin 提供的类。您无需在用例中添加任何内容。

打印productquantity 的功能应该是ShoppingCart 的一个功能,所以只需:

class ShoppingCart{
    private val productAndQuantityList = mutableListOf<Pair<Product,Int> >()
    // ...
    fun printContents() {
        for ( (product,quantity) in productAndQuantityList) {
            println("Name: ${product.productName}")
            println("Quantity: $quantity")
        }            
    }
}

【讨论】:

  • 感谢您的解释,这意味着我不需要创建 Pair 类,因为它是 Kotlin 提供的类,是吗?
  • @user12595983 是的。 Pairs 和 Triples 是 Kotlin 标准库的一部分。 Pairs 甚至在构建地图时还有第二个用例,并且还有一个 to 中缀函数。因此你可以写val myMap = mapOf("key1" to "value1", "key2" to "value2")来定义一个Map,相当于val myMap = mapOf(Pair("key1", "value1"), Pair("key2","value2"))
猜你喜欢
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多