MutableMap< String,Any?当我在Kotlin中使用委托时,将值传递给var吗? [英] How does MutableMap<String, Any?> pass value to var when I use delegate in Kotlin?
问题描述
以下示例代码来自网页.我了解这些var _id,城市和国家/地区可以通过代表获得价值.
The following sample code is from a webpage. I understand that these vars _id, city and country get value by delegate.
我不明白地图如何:MutableMap将值传递给这些vars _id,城市和国家/地区?
I can't understand how map: MutableMap pass value to these vars _id, city and country ?
我必须先传递这些键的值才能进行映射吗?例如map ["_ id"] = 132L,map ["city"] ="Wuha"和map ["country"] ="USA"?
Do I must pass value of these key to map first ? such as map["_id"]=132L, map["city"]="Wuha" and map["country"]="USA"?
如果没有map ["_ id"]会发生什么?代码var _id: Long by map
会导致错误吗?
What happened if there is no map["_id"] ? will the code var _id: Long by map
cause error?
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
}
}
推荐答案
首先,您需要了解委托属性的工作方式.对象不直接拥有委托的属性.它仅拥有委托.例如,var _id: Long by map
实际上看起来像
First, you need to understand how delegated property works. Object does not own the delegated property directly. It only owns the delegate. For example, var _id: Long by map
is actually look like
var _id: Long
get() {
val value = map["_id"] as? Long
if (value == null)
throw Excecption()
return value
}
set(value) {
map["_id"] = value
}
我必须先传递这些键的值才能进行映射吗?例如map ["_ id"] = 132L,map ["city"] ="Wuha"和map ["country"] ="USA"?
Do I must pass value of these key to map first ? such as map["_id"]=132L, map["city"]="Wuha" and map["country"]="USA"?
否,就像lateinit
一样,这是一个运行时检查.
No, it is a run-time check, just like lateinit
.
如果没有map ["_ id"]会发生什么?代码var _id:Long by map会导致错误吗?
What happened if there is no map["_id"] ? will the code var _id: Long by map cause error?
当然会有一个例外.
请注意,对于普通班级,建议不.它是为JSON反序列化而设计的(尽管我仍然更喜欢GSON).不建议这样做,因为您正在创建潜在的运行时异常,可以避免这种异常,包括缺少值和类型检查.
Note that this is NOT recommended for normal class. It is designed for JSON deserialization (I still prefer GSON though). It is not recommended because you are creating potential run-time exception which can be avoid, including missing value and type checking.
此外,如果不需要显式使用HashMap()
,则应使用mutableMapOf()
而不是HashMap()
.
Also, you should use mutableMapOf()
instead of HashMap()
if you does not need HashMap()
explicitly.
这篇关于MutableMap< String,Any?当我在Kotlin中使用委托时,将值传递给var吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!