Kotlin hashMapOf()
In Kotlin, the hashMapOf()
function is used to create a new mutable HashMap
. This function returns a reference to the newly created HashMap
. You can specify the initial values of the HashMap
while creating it using the hashMapOf()
function.
Syntax
The syntax of the hashMapOf()
function is as follows:
fun <K, V> hashMapOf(vararg pairs: Pair<K, V>): HashMap<K, V>
where:
K
is the key type.V
is the value type.pairs
are the pairs of key-value entries to be added to theHashMap
.
Example
Here's an example of using the hashMapOf()
function to create a new HashMap
:
val fruits = hashMapOf(
Pair("apple", 10),
Pair("banana", 20),
Pair("orange", 30)
)
In the above example, we created a new HashMap
called fruits
. The keys are String
values representing the names of fruits, and the values are Int
values representing the quantity of each fruit.
Output
When you run the above example, no output will be produced. The hashMapOf()
function simply returns a reference to the newly created HashMap
.
Explanation
The hashMapOf()
function is a convenient way to create a new mutable HashMap
in Kotlin. You can specify the initial values of the HashMap
while creating it using the hashMapOf()
function by passing a list of Pair
objects representing the key-value entries.
In the example above, we created a new HashMap
called fruits
and initialized it with three key-value entries using Pair
objects. You can access the values in the HashMap
using their corresponding keys.
Use
The hashMapOf()
function is useful when you need to create a new mutable HashMap
in Kotlin and optionally initialize it with some key-value entries.
You can use mutable HashMaps
to store and manipulate key-value pairs. HashMaps are often used in scenarios such as:
- Storing configuration data
- Caching frequently used data
- Maintaining session data
Important Points
- The
hashMapOf()
function returns a reference to the newHashMap
that has been created. - You can specify the initial values of the
HashMap
while creating it using thehashMapOf()
function. - The keys in the
HashMap
must be unique. If you add a key that already exists, the existing value will be overridden with the new value.
Summary
In this tutorial, we discussed the hashMapOf()
function in Kotlin, which is used to create a new mutable HashMap
and optionally initialize it with some key-value entries. We covered the syntax, example, output, explanation, use, and important points about the hashMapOf()
function. With this knowledge, you can now create and initialize new HashMaps
in Kotlin.