如何在Kotlin中为_id赋值?

时间:2017-09-29 07:37:24

标签: kotlin

代码1是来自网页的示例代码。为了简化问题,我制作了代码2

在代码2中,代码段var _id: Long by map让我感到困惑,val地图为MutableMap<String, Any?>,_id为Long,为什么地图会为_id分配值?

代码1

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
    }
}

代码2

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   
}

致Grzegorz Piwowarek ,代码3是对吗?

代码3

val map: MutableMap<String, Any?>
var _id: Long by map
map=hashMapOf("_id" to 123)  
println(_id) 

1 个答案:

答案 0 :(得分:3)

因为它是语言功能之一 - 委托属性。

Kotlin默认情况下并不会真正公开类字段,而是通常由字段支持但也可以通过地图支持的属性。

val id = CityForecast(hashMapOf("_id" to 123), emptyList())._id
println(id) // 123

但如果您尝试运行:

CityForecast(hashMapOf("_id" to 123), emptyList()).city

你会得到:

java.util.NoSuchElementException: Key city is missing in the map.