2
votes

I can't understand What different there are between MutableMap and Map in Kotlin?

The following code is from a sample on https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/data/db/DbClasses.kt

I don't know why val map is designed as MutableMap, I think it should be Map because it's field of database table.

Could you tell me why var map is designed as 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
    }
}
3

3 Answers

3
votes

MutableMap is the mutable version of Map, so if you use MutableMap you can modify, change element values, and so on

For example :

  1. Adding new values to element
val person = mutableMapOf("Kelvin" to 19)
person["Kelvin"] = 25
println(person) // {Kelvin=25}
  1. Adding new key, value pair to the map
person["angel"] = 17
println(person) // {Kelvin=25, angel=17}
  1. Remove element from the map
person.remove("Kelvin")
println(person) // {angel=17}

You can't do these if you use the immutable version of map which is Map

2
votes

I see your confusion - val and var define pointer mutability - i.e. val always points to the same object in memory - while it doesn't say anything about if that object can or cannot change its properties. var states that your variable can change/point to different objects.

When you declare your map like this:

val cities = mutableMapOf(1 to "Paris", 4 to "Rome", 2 to "Viena", 3 to "Barcelona")  

then you can add or remove elements in this map, since, it's mutable. But you can't change the pointer to a different collection.

Image if you have two maps representing European cities and US cities:

val citiesEu = mutableMapOf (1 to "Paris", 4 to "Rome", 2 to "Viena", 3 to "Barcelona")  

val citiesUS = mutableMapOf(1 to "New York", 4 to "L.A.", 2 to "Dallas", 3 to "Washington")

val myCities = mutableMapOf<Int, String>() 

which you need to switch according to selected state,something like this:

if (code == "US") 
    myCities = citiesUS 
else 
    myCities = citiesEU

you won't be able to do this because of val (cannot be reassigned), you'd need to change it into: var myCities = mutableMapOf()

0
votes

Map is read only. MutableMap is mutable. Because var can be written a new value, it has to be a mutable variable as delegate property. If you only uses delegate property on val, you can use a Map instead.