kotlin collection literals

Kotlin Collection Literals

Kotlin provides collection literals as a convenient way to initialize collections with predefined values. Collection literals allow you to define lists, sets, and maps directly in your code without explicitly calling their constructors or using builder methods.

Here are the different types of collection literals in Kotlin:

  1. List Literals: List literals are used to create immutable lists. They are defined using square brackets [] and separating the elements with commas. For example: kotlin val numbers = [1, 2, 3, 4, 5]

  2. Set Literals: Set literals are used to create immutable sets. They are defined using curly braces {} and separating the elements with commas. For example: kotlin val fruits = {"apple", "banana", "orange"}

  3. Map Literals: Map literals are used to create immutable maps. They are defined using curly braces {} with key-value pairs separated by commas. The key and value are separated by a colon :. For example: kotlin val person = {"name": "John", "age": 30, "city": "New York"}

It's important to note that collection literals create immutable collections by default. If you need to modify the collection later, you can use the toMutableList(), toMutableSet(), or toMutableMap() functions to convert them into mutable collections.

These collection literals provide a concise and readable way to initialize collections with predefined values in Kotlin.