HelloCW
HelloCW

Reputation: 2325

How can map assign value to _id in Kotlin?

The Code 1 is a sample code from webpage. In order to simplify the question, I make the Code 2

In Code 2, the snippet var _id: Long by map make me confused , the val map is MutableMap<String, Any?> and _id is Long, why can the map assign value to _id ?

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

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

To Grzegorz Piwowarek , is the code 3 right?

Code 3

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

Upvotes: 0

Views: 635

Answers (1)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13823

Because it's one of the language features - Delegated Properties.

Kotlin does not really expose class fields by default but properties which are usually backed by fields but can be backed... by a map as well.

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

but if you try to run:

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

you will get:

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

Upvotes: 3

Related Questions