如何在Kotlin中将值分配给_id?

代码1是来自网页的示例代码。 为了简化这个问题,我做了Code 2

在代码2中,片段var _id: Long by map让我感到困惑,val map是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) 

因为这是语言功能之一 – 委派属性。

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.