Kotlin mapOf()
In Kotlin, mapOf()
is a function that returns an immutable map of key-value pairs. The function takes any number of arguments, where each argument is a pair of key and value separated by a comma. In this tutorial, we'll discuss how to use mapOf()
in Kotlin.
Syntax
The syntax for mapOf()
is as follows:
val mapName = mapOf(key1 to value1, key2 to value2, ..., keyN to valueN)
where mapName
is the name of the map, key
is the unique identifier for the value, and value
is the value to be associated with the key.
Example
Let's see an example of how to use mapOf()
in Kotlin:
val fruits = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
println(fruits)
Output:
{apple=1, banana=2, cherry=3}
In this example, we created a map called fruits
with three key-value pairs. The keys are strings representing fruit names and the values are integers representing their quantity. When we print the fruits
map, we get the output as {apple=1, banana=2, cherry=3}
.
Explanation
In Kotlin, maps are a collection of key-value pairs where each key is unique and associated with a single value. Maps can be mutable or immutable, with immutable maps being created using mapOf()
.
To create a new map using mapOf()
, we specify the key-value pairs separated by commas enclosed in parentheses. Each pair is separated by the keyword to
. In the example above, apple
is the key and 1
is the value, separated by the keyword to
.
Once we have created the map, we can access the elements using their respective keys. In this case, we can access the value of apple
using the syntax fruits["apple"]
.
Use
mapOf()
is used to create immutable maps in Kotlin. Immutable maps are useful in scenarios where we want to store a fixed set of values and don't want them to be modified over time. We can use mapOf()
to define constants, lookup tables, or configurations for our programs.
Important Points
mapOf()
creates an immutable map, which means that the key-value pairs cannot be modified once the map is created.- Keys and values can be of any type in Kotlin, but they must be consistent throughout the map.
- To add or remove elements from a map, we can use the mutable map functions
put
andremove
, respectively.
Summary
In this tutorial, we discussed how to use mapOf()
to create immutable maps in Kotlin. We covered the syntax, example, output, explanation, use, and important points of the mapOf()
function. With this knowledge, you can now create and use maps in Kotlin to store a set of key-value pairs.