首页 文章

在Kotlin中MutableMap和Map有什么不同?

提问于
浏览
0

我无法理解MutotMap和Kotlin中的Map有什么不同?

以下代码来自https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/data/db/DbClasses.kt上的示例

我不知道为什么val map被设计为MutableMap,我认为它应该是Map,因为它是数据库表的字段 .

你能告诉我为什么var map被设计为MutableMap吗?

class CityForecast(val map: MutableMap<String, Any?>, val dailyForecast: List<DayForecast>) {
    var _id: Long by map
    var city: String by map
    var country: String by map

    constructor(id: Long, city: String, country: String, dailyForecast: List<DayForecast>)
            : this(HashMap(), dailyForecast) {
        this._id = id
        this.city = city
        this.country = country
    }
}

1 回答

  • 0

    Map 是只读的 . MutableMap 是可变的 . 因为 var 可以写成新值,所以它必须是一个可变变量作为委托属性 . 如果您仅在 val 上使用委托属性,则可以使用 Map .

相关问题