Arrays
Published Jan 20, 2023
Contribute to Docs
Arrays are collections of items of the same data type with 0-based indexing that are stored at contiguous memory locations.
Syntax
// Array class instance
arrayOne = arrayOf<Type>(values)
arrayTwo = Array(size) iteratorFunction
// Array of primitive types
arrayThree: TypeArray = typeArrayOf(values)
arrayFour = TypeArray(size) iteratorFunction
Instances of the Array
class are created in either of the following ways:
- The
arrayOf()
function accepts an optional<Type>
and a comma-separated list ofvalues
. - With the
Array()
class constructor that accepts asize
parameter and aniteratorFunction
for populating the array.
Arrays of primitive type values can also be created:
- In lieu of
TypeArray
, actual class names (e.g.,IntArray
) should be used for typing or constructing the new array.- The
TypeArray()
constructor uses asize
parameter as well as aniteratorFunction
.
- The
- The
typeArrayOf()
function uses a list ofvalues
to create an array of a certain data type (e.g.,intArrayOf()
).
Example
The following example uses the Array()
class constructor to create and populate a num
array. The elements are then printed:
fun main() {val num = Array(5, {i-> i*1})for (i in 0..num.size - 1) {print(" " + num[i])}println()}
This prints the following output:
0 1 2 3 4
Arrays
- .forEach()
- Iterates over elements in a collection and performs a specified action on each element, without producing a new collection.
- .get()
- Returns the element located at a given position in an array.
- .indices
- Returns a range indicating the valid indices in an array.
- .map()
- Transforms elements in a collection by applying a specified transformation function, resulting in a new collection with the transformed values.
- .reverse()
- Reverses the order of the elements in-place in a specified array.
- .size
- Calculates the number of elements in an array.
- .slice()
- Creates a new list containing elements from the specified range or indices of an array.
- .sort()
- Returns a sorted array, modifying the original array in-place to arrange its elements in ascending order.
- arrayOf()
- Creates a new array containing the specified elements.
- arrayOfNulls()
- Creates an array of a specified size with all elements initialized as null.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours