Kotlin中如何引用其他类的属性?动物园类访问动物类属性问题
解决Zoo类中遍历Animal的adoptionen列表计算总领养费用问题
你的核心问题是没有通过当前的Animal实例访问它的adoptionen列表,直接写adoptionen会导致编译器找不到这个变量——因为它是Animal类的成员属性,必须绑定到具体的实例上。
修正后的基础实现
直接在循环中通过每个Animal对象t访问其adoptionen列表即可:
class Zoo { var tiere = mutableListOf<Animal>() fun getTotalAdoptionMoney(): Double { var totalMoney = 0.0 for (t in tiere) { // 通过当前Animal实例t访问它的adoptionen列表 for (a in t.adoptionen) { totalMoney += a.price } } return totalMoney } }
更简洁的Kotlin函数式实现
利用Kotlin的集合API可以大幅简化代码,避免嵌套循环:
class Zoo { var tiere = mutableListOf<Animal>() fun getTotalAdoptionMoney(): Double { return tiere.sumOf { animal -> animal.adoptionen.sumOf { it.price } } } }
这里用了两层sumOf:
- 外层
sumOf遍历tiere中的每个Animal - 内层
sumOf遍历当前Animal的adoptionen列表,累加所有price值
额外注意点
确保Adoption接口已经定义了price属性(因为你的代码中直接使用了a.price),比如:
interface Adoption { val price: Double }
内容的提问来源于stack exchange,提问作者Zel
相关产品推荐
相关产品推荐

