You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 外层sumOf遍历tiere中的每个Animal
  2. 内层sumOf遍历当前Animal的adoptionen列表,累加所有price值

额外注意点

确保Adoption接口已经定义了price属性(因为你的代码中直接使用了a.price),比如:

interface Adoption {
    val price: Double
}

内容的提问来源于stack exchange,提问作者Zel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:12:08