![]() ![]() This example shows how even complex operations can be performed easily with Kotlin’s powerful APIs. We’re making use of the with scope function here to keep our code tidy. This tutorial covers Kotlin Map collection, covering types of map, Mutable and immutable map and using mapOf() and mutableMapOf() functions and other. Maps are used to hold the pairs of objects in the form of key/value. Sales.forEach ĪssertEquals(17, inventory) // 24 - 7 + 0ĪssertEquals(13, inventory) // 14 - 4 + 3ĪssertEquals(11, inventory) // 9 - 5 + 7ĪssertEquals(5, inventory) // 0 - 0 + 5 The map is an interface and a collection in Kotlin. Map keys are unique the map holds only one value for each key. A map is a collection that holds pairs of objects. Read-only maps are created with mapOf and mutable maps with mutableMapOf. Val shipments = mapOf("Chocolate" to 3, "Strawberry" to 7, "Rocky Road" to 5) Kotlin distinguishes between read-only and mutable maps. ![]() We’ll subtract all the entries in the sales map and then add all the entries from the shipments map to update each flavor’s Quantity: val sales = mapOf("Vanilla" to 7, "Chocolate" to 4, "Strawberry" to 5) After a day of receiving shipments and selling ice cream, we need to update our store’s inventory map. The forEach method performs an action on each entry in a given map. In the next tutorial we will discuss about sets in Kotlin.As a final example, we’ll use what we’ve learned already and introduce the forEach method. In this tutorial we discussed about immutable and mutable maps, their creation using mapOf() and mutableMapOf() functions and some important functions provided. ![]() Let us create immutable map using these two functions: fun main() The mapOf() is used to create a specific map with keys and values of K and V data types respectively. Similar to lists, the mapOf() function is used to create a general map where key and value can be of any data type. Basically, the mapOf is nothing but an inline function that returns emptyMap (). In Kotlin immutable maps are created using mapOf() and mapOf() functions. Immutable maps are created using Map interface. In Kotlin we can have both a mutable map and an immutable map. The to keyword is used to map a key to a value.Ī key value pair is also known as an entry. The key and value can be of different data type. The key should be unique and only one value can be stored for each unique key. Maps are used to store key and value pairs. In this tutorial we will discuss about Kotlin Map. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |