Mutable list and Immutable list in kotlin android

 The Kotlin List helps the developer read and write data locally. There are two types of lists available in Kotlin. A list that is used only for reading purposes is called an immutable list. A mutable list is a list where the developer can write data.

Lists are part of the Kotlin Collection. Kotlin collections are defined in three forms. These are ListsSets , Maps. In this article, we will learn about Kotlin lists and their functionality. To know more about kotlin collection then click the link. 

Kotlin Collections come in three primary forms: Lists, Maps, and Sets. Each is a distinct type, with its unique characteristics and use cases. Here they are:

Kotlin List

  • Kotlin List is a sequential arrangement of elements that permit duplicate values, preserving the order in which they are added.
  • Elements in a list are accessed by their index, and you can have multiple elements with the same value.
  • Lists are a great help when storing a collection of items whose order needs to be maintained – for example, a to-do list – and storing duplicate values.

Kotlin Map

  • Kotlin Map are collections of key-value pairs. In lightweight language, a method allows us to link values with distinct keys, facilitating effortless retrieval of values using their corresponding keys.
  • The keys are also ideal for efficient data retrieval and mapping relationships between entities.
  • Common use cases of Kotlin Maps include building dictionaries, storing settings, and representing relationships between objects.

Kotlin Set

  • Kotlin Set is an unordered collection of distinct elements, meaning it does not allow duplicate values.
  • Sets are useful when you need to maintain a unique set of elements and do not require a specific order for those elements.
  • Common use cases of Kotlin Sets include tracking unique items, such as unique user IDs, or filtering out duplicates from a list.

The choice between Kotlin lists, maps, and sets depends on your specific data requirements. Lists are suitable for ordered collections with potential duplicates, maps are ideal for key-value associations, and sets are perfect for maintaining unique, unordered elements.

Create an immutable list 

fun main(args: Array<String>) {
//initialize the list
var listOfAnimal = listOf<String>("Cow", "Dog", "Goat")
// print the list
println(listOfAnimal)
}


Retrieve the value in the immutable list:


fun main(args: Array<String>) {
//initialize the list
var listOfAnimal = listOf<String>("Cow", "Dog", "Goat")
// using [] brackets
println(listOfAnimal[0])

}

Create a mutable list:


fun main(args: Array<String>) {
// initialize the list
var listOfAnimal = mutableListOf<String>("Cow", "Dog", "Goat")
// print the list
println(listOfAnimal)
}

Comments

Popular posts from this blog

Disable/Hide Year from DatePickerDialog in android

Coordinator Layout in Android

Custom Calendar in android