- Constructing collections
- Create with collection builder functions
- Empty collections
- Initializer functions for lists
- Concrete type constructors
- Copy
- Invoke functions on other collections
- Declare an empty array in Kotlin
- 1. Using emptyArray() function
- 2. Standard library function
- 3. Array constructor
- 4. Using arrayOfNulls() function
- Arrays
- Primitive type arrays
Constructing collections
The most common way to create a collection is with the standard library functions listOf() , setOf() , mutableListOf() , mutableSetOf() . If you provide a comma-separated list of collection elements as arguments, the compiler detects the element type automatically. When creating empty collections, specify the type explicitly.
The same is available for maps with the functions mapOf() and mutableMapOf() . The map’s keys and values are passed as Pair objects (usually created with to infix function).
Note that the to notation creates a short-living Pair object, so it’s recommended that you use it only if performance isn’t critical. To avoid excessive memory usage, use alternative ways. For example, you can create a mutable map and populate it using the write operations. The apply() function can help to keep the initialization fluent here.
Create with collection builder functions
Another way of creating a collection is to call a builder function – buildList() , buildSet() , or buildMap() . They create a new, mutable collection of the corresponding type, populate it using write operations, and return a read-only collection with the same elements:
val map = buildMap < // this is MutableMap, types of key and value are inferred from the `put()` calls below put("a", 1) put("b", 0) put("c", 4) > println(map) //
Empty collections
There are also functions for creating collections without any elements: emptyList() , emptySet() , and emptyMap() . When creating empty collections, you should specify the type of elements that the collection will hold.
Initializer functions for lists
For lists, there is a constructor-like function that takes the list size and the initializer function that defines the element value based on its index.
fun main() < //sampleStart val doubled = List(3, < it * 2 >) // or MutableList if you want to change its content later println(doubled) //sampleEnd >
Concrete type constructors
To create a concrete type collection, such as an ArrayList or LinkedList , you can use the available constructors for these types. Similar constructors are available for implementations of Set and Map .
Copy
To create a collection with the same elements as an existing collection, you can use copying functions. Collection copying functions from the standard library create shallow copy collections with references to the same elements. Thus, a change made to a collection element reflects in all its copies.
Collection copying functions, such as toList() , toMutableList() , toSet() and others, create a snapshot of a collection at a specific moment. Their result is a new collection of the same elements. If you add or remove elements from the original collection, this won’t affect the copies. Copies may be changed independently of the source as well.
These functions can also be used for converting collections to other types, for example, build a set from a list or vice versa.
Alternatively, you can create new references to the same collection instance. New references are created when you initialize a collection variable with an existing collection. So, when the collection instance is altered through a reference, the changes are reflected in all its references.
Collection initialization can be used for restricting mutability. For example, if you create a List reference to a MutableList , the compiler will produce errors if you try to modify the collection through this reference.
fun main() < //sampleStart val sourceList = mutableListOf(1, 2, 3) val referenceList: List
Invoke functions on other collections
Collections can be created as a result of various operations on other collections. For example, filtering a list creates a new list of elements that match the filter:
Mapping produces a list from a transformation’s results:
For more information about operations on collections in Kotlin, see Collection operations overview.
Declare an empty array in Kotlin
This article explores different ways to declare an empty array in Kotlin.
1. Using emptyArray() function
The standard approach in Kotlin to get an empty array of the specified type is using the emptyArray() function.
2. Standard library function
Alternatively, we can use the Kotlin standard library function to generate an empty array. There are several functions to construct an array, each for respective data types – doubleArrayOf() , floatArrayOf() , longArrayOf() , intArrayOf() , charArrayOf() , shortArrayOf() , byteArrayOf() , and booleanArrayOf() .
To create a typed array, use the arrayOf() function:
3. Array constructor
We can also use the array constructor with the specified size 0 to create an empty array.
To create a typed array, use the Array constructor as follows:
We can even create an empty two-dimensional array containing non-empty arrays. For example, the following code creates a two-dimensional array of length 0, containing IntArray values:
4. Using arrayOfNulls() function
Finally, we can use the arrayOfNulls() function to create an array of the specified size and the specified type, initialized with null .
That’s all about declaring an empty array in Kotlin.
Average rating 5 /5. Vote count: 10
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂
This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it
Arrays
Arrays in Kotlin are represented by the Array class. It has get() and set() functions that turn into [] by operator overloading conventions, and the size property, along with other useful member functions:
To create an array, use the function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3] . Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.
Another option is to use the Array constructor that takes the array size and the function that returns values of array elements given its index:
The [] operation stands for calls to member functions get() and set() .
Arrays in Kotlin are invariant. This means that Kotlin does not let us assign an Array to an Array , which prevents a possible runtime failure (but you can use Array , see Type Projections).
Primitive type arrays
Kotlin also has classes that represent arrays of primitive types without boxing overhead: ByteArray , ShortArray , IntArray , and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function:
// Array of int of size 5 with values [0, 0, 0, 0, 0] val arr = IntArray(5) // Example of initializing the values in the array with a constant // Array of int of size 5 with values [42, 42, 42, 42, 42] val arr = IntArray(5) < 42 >// Example of initializing the values in the array using a lambda // Array of int of size 5 with values [0, 1, 2, 3, 4] (values initialized to their index value) var arr = IntArray(5) < it * 1 >