Maps
Learn how to use maps, find values using keys, and add new elements to maps.
Key-value mapping
We use maps to keep associations from keys to their values. For instance:
From user ID to an object representing the user
From a website to its IP address
From a configuration name to data stored in this configuration
Press + to interact
class CachedApiArticleRepository(val articleApi: ArticleApi) {val articleCache: MutableMap<String, String> =mutableMapOf()fun getContent(key: String) =articleCache.getOrPut(key) {articleApi.fetchContent(key)}}class DeliveryMethodsConfiguration(val deliveryMethods: Map<String, DeliveryMethod>)class TokenRepository {private var tokenToUser: Map<String, User> = mapOf()fun getUser(token: String) = tokenToUser[token]fun addToken(token: String, user: User) {tokenToUser[token] = user}}
Creating maps
We can create a map using the mapOf
function and then use key-value pairs as arguments to specify key-value associations. For instance, we might ...