In this section, we will learn what the Arrays are and how to use them in Kotlin.
What is Array in Kotlin?
An array is a type of value (an object) that can hold multiple other values!
So far, we know that if we want to store a value in a program, we can use variables, right?
Well, if you have multiple values, you probably create multiple variables and store each value in a separate variable.
But if those values are related to each other (for example a list of female names or a list of fruits etc.) we can create an Array and store all of those values in just one place (inside the array).
Now, using the array, we can easily access those values to either read them or change them to something else.
Notes:
- Arrays are fixed in size! This means the moment you set the size of an array, you can’t change it dynamically at runtime. For example, if an array is set to have 10 elements, the array won’t be able to take more than 10 elements at runtime.
- When creating an array, you have this option to create an array that all of its elements are of the same type (like an array that all its elements are of type String or of type Integer etc.) Or you can have an array with mixed type of elements. (We will see how to create both types of arrays).
How to Declare Arrays in Kotlin?
Based on situations, there are two ways to create an array in Kotlin:
- If you know in advance what the values are to be stored in an array, then you can call the arrayOf or
arrayOf<>()
functions and create an array using those values. - But if you don’t know what the values are until at runtime, then you can use the arrayOfNull<>() function which is a generic function and we can use that to set the length of the array first and then at runtime add the elements.
Array declaration using the arrayOf() and arrayOf<>() functions in Kotlin
The first method of creating an array is by using the arrayOf() function.
As mentioned, this method is used when we know in advance the values we want to put to the target array.
This is the syntax of this function:
var newArray = arrayOf(value1, value2, value3, value_n)
Here, the arguments to this function are the elements we want to assign to the target array.
For example, if the elements of the function are “Omid”, “Jack”, “Ellen” then this means the target array will have these three elements within its body.
Note that using the arrayOf() function, the data type of elements can be mixed! For example, you can have a bunch of elements of the array set to type Integer while others be String, etc.
On the other hand, if you want to make sure the data type of the values will stay the same (meaning at runtime users can only assign one type of value into the variable) then you can use the arrayOf<>()
function.
The main difference between arrayOf and arrayOf<>() functions is that the latter has a symbol <>
where you put the data type of the elements you want to have in your array, inside this symbol. For example, if the purpose is to have an array of string, then the value we put inside this symbol will be String`
. This way, the new array will only accept string values and any attempt to add other types of values will result in error.
Note: when explicitly adding the elements of an array at its creation time, this action will set the length of the target array as well! For example, if you passed 10 arguments to this function, that means the array will have a length of 10 elements.
Example: creating array in Kotlin using the arrayOf() function
fun main(){ var names = arrayOf<String>("Jack","Omid","Ellen","Elon") var numbers = arrayOf<Int>(1,2,3,4,5,6,7). var myArray4= arrayOf(1,10,4, "Monica","Peter") }
Here we have three arrays named names
, numbers
and myArray4
.
The first array contains 4 names of type String (So the type of the elements is String and its length is fixed to 4).
The second array contains 7 elements and all of them are of type Integer.
The third array however, is of mixed type and it contains values of types Integer and String.
Later in this section, we will explain how to access and change these values.
Note that elements within an array have index numbers! For example, the first element of an array is stored in the index number 0, the second element will be at the index 1, the third element will be at index 2 and so on. As you’ll soon see, we use this index number to access the elements of an array.
Array declaration using the arrayOfNulls<>() function in Kotlin
The next method of creating an array is by using the arrayOfNulls<>() function.
The <>
symbol you see after the name of the function is to signal that the function is a generic one.
In the Kotlin generic functions, we’ll explain what it means to have a generic function, but in short, this type of function is capable of working with many data types! For example, if you create a typical function and set its parameters to Integer, you’re limited to just passing integer values to the function, but for a generic function, you can pass any type of value as the argument of that function (if the parameters are set to generic of course).
This is how we can use the arrayOfNulls function:
var arrayVariable = arrayOfNulls<data-type>(length)
The value we set in the <>
symbol defines the data type of elements that we will add to the array at runtime. For example, if we want elements to be of type String, then we put the value String
in the <>
.
Also, the value we put as the argument of the function sets the length of that array. For example, if we want to have an array of 10 elements, then we set the value 10 as the argument of the function.
Example: creating array in Kotlin using the arrayOfNulls<>() function
fun main(){ var names = arrayOfNulls<String>(10) var numbers = arrayOfNulls<Int>(20) }
Here the names
array is holding an array of 10 elements and all of them are of type String. Note that at the moment, the array only contains enough space to hold 10 string elements, but there’s no string value in it at this time. Basically, we need to use specific functions to add elements into the array.
For the second array numbers
, the data type is set to Int, which means it can only hold Integer values and also the length is set to 20 and that means you can only put 20 integer numbers into this array at runtime.
Access and Change the Elements of an Array in Kotlin
In order to access the elements of an array, you have two options:
The first one is to use a pair of braces []
after the name of the target array as:
array_name[index].
Here the array_name is the name of the array we want to access its elements.
[index]
: within the braces that comes after the name of the array, we put an integer number. This integer number is the index number of the element in the array we want to access it. For example, if the element is set at the index 2, then the value we set as the argument of the []
would be 2.
Now, if you use this syntax on the left side of an assignment operator like =
, that means you want to change the value that is currently in that position.
For example:
array_name[5] = newValue
Here, the element with the index number 5 in the array_name will be replaced with the value newValue
.
But other than on the left side of the assignment operator, in any other places we call an array, it will return the value that is currently stored in that index position.
For example:
println(array_name[10])
Here, your program will invoke the current value in the index number 10 of the array_name and pass that value as the argument of the println() function.
Example: accessing and changing Kotlin Array Elements using a pair of braces []
fun main(){ var names = arrayOf("Omid","Jack","Ellen", 20, true, false, 50) names[0] = 10 names[1] = 20 println(names[0]) println(names[1]) println(names[2]) }
Output:
10 20 Ellen
In this example, using the []
we’ve changed the value of the first and second element of the names
array and also sent the first three elements of this array to the output stream.
Kotlin Arrays: Access and Change Elements of an Array using get() and set() Functions
The second method of accessing the elements of an array is by using the get() and set() functions.
The get() and set() functions belong to the array you create. So they can be called using the target arrays.
The get() function is used to return a value from the target array. It takes the index number of the element that we want to retrieve as its argument and will return the element in that index position.
For example:
array_name.get(10)
This call will return the element in the index number 10 of the array_name.
On the other hand, the set()
function is used to replace the current value in a specific index.
The function takes two arguments:
- The first argument is the position where we want to change the current value there.
- The second argument is the new value we want to put in that index.
For example:
array_name.set(2, 50)
This call means put the value 50 in the index number 2 of the array_name.
Example: accessing and changing Kotlin Array Elements using get() and set() functions
fun main(){ var names = arrayOf("Omid","Jack","Ellen", 20, true, false, 50) names.set(0,10) names.set(1, 20) println(names.get(0)) println(names.get(1)) println(names.get(2)) }
Output:
10 20 Ellen
The example above is the refactor of the last example we’ve seen using the []
. But this time we’ve used the get
and set
functions to access and change the elements of the array.
Array Length in Kotlin
As mentioned before, the number of elements that an array can store is called the length of the array.
For example, if the array is capable of storing 10 elements, then the length of that array is 10.
We can get the length of the target array using the size property.
Simply invoke this property on top of the target array and it will return its length.
Also, there’s a function called count()
by which we can get the same result.
Example: getting the length of an array in Kotlin
fun main(){ var names = arrayOf("Omid","Jack","Ellen", 20, true, false, 50) var companies = arrayOfNulls<String>(4) companies[0] = "Apple" companies[1] = "Microsoft" companies[2] = "Tesla" companies[3] = "Google" println("The length of the names array is: ${names.count()}") println("The length of the companies array is: ${companies.size}") }
Output:
The length of the names array is: 7 The length of the companies array is: 4
Kotlin val Keyword and Arrays
So far, every array we’ve created was using the var
keyword. But we can use the val
keyword to create an array too.
Be aware that, when creating an array using the val keyword, the variable that is pointing to the target array cannot be reassigned. But the elements in the arrays itself can be changed to other values.
Example: creating arrays using val keyword
fun main(){ val names = arrayOf("Omid","Jack","Ellen", 20, true, false, 50) names[3] = "John" names[4] = "Monica" names[5] = "James" names[6] = "Jeremy" for (element in names){ println(element) } }
Output:
Omid Jack Ellen John Monica James Jeremy
As you can see, even though the variable names
is created using the val
keyword, we could change the elements of the array itself to anything we wanted.
Just remember that a variable that is created using the val keyword cannot point to any other array except the one that is already pointing.
Passing Arrays to a Function in Kotlin
An array can be passed to a function as its argument as well.
Now, in order to set the data type of a parameter in a function to an Array type, we use the Array<data-type>
syntax.
Basically, we use the Array class and after that comes the <>
symbol and in it we set the data type that the target parameter should expect to get.
For example, if a parameter of a function is set to take an array of type String then this is how we set the type of that parameter:
fun functionName(parameter:Array<String>){…}
Or if the parameter is set to take an array of type Int, then we only need to set the value within the <> symbol to Int like:
fun functionName(parameter:Array<Int>){…}
Also, if the array has elements of multiple different data types, we set the value of the <>
to Any
as:
fun functionName(parameter:Array<Any>){…}
In the Kotlin and inheritance section, we will explain the Any
keyword.
Remember that when passing an array to a function, you’re only passing a reference to that function! This means the parameter of the target function has the access to the original array and not a copy of it! So if inside the target function we changed the value of one or more indexes of the array, this change will be reflected on the main array. So any variable that has the access to the original array will see this change.
Example: passing arrays to functions in Kotlin
fun main(){ val names = arrayOf<String>("Omid","Jack","Ellen") changeArray(names) for (element in names){ println(element) } } fun changeArray(arr:Array<String>){ arr[0] = "Elon" arr[1] = "Peter" }
Output:
Elon Peter Ellen
In this example as you can see we’ve used the arr
parameter to change the values of the first and second indexes of the array within the body of the changeArray
function and this change appeared when called the names
variable and set it as the collection of the for loop.
Returning an Array from a Function in Kotlin
An array can be returned from a function as well.
To do that, just make sure that:
- First of all, the return data type of the function in its signature is set to: Array<data-type> where the data-type defines the type of the elements of the target array we want to return from the function.
- Second, use the return statement and pass a reference of the target array (like the variable that holds the array) as the argument of this statement. Also, make sure the type of elements in the array is the same as the type we set in the signature of the function.
Example: returning an array from a function in Kotlin
fun main(){ val names = listOfNames() for (element in names){ println(element) } } fun listOfNames():Array<String> { var list = arrayOf<String>("Omid","Jack","Ellen", "Peter","Elon") return list }
Output:
Omid Jack Ellen Peter Elon
Kotlin ArrayIndexOutOfBoundException
The ArrayIndexOutOfBoundException is an error (AKA exception) that you’ll get if you try to access an index number of an array that is out of range of that array!
For example, let’s say we have an array of 10 elements; Now, if we try to access the index number 30 to either get or update its value, we will get this error! This is because the array has only 10 indexes (0 to 9) and we’re trying to access an index that does not exist! Hence, the error will be thrown.
Example: throwing ArrayIndexOutOfBoundException
fun main(){ val names = listOfNames() for (element in names){ println(element) } } fun listOfNames():Array<String> { var list = arrayOf<String>("Omid","Jack","Ellen", "Peter","Elon") list[21] = "Jack" return list }
Output:
ArrayIndexOutOfBoundsException: Index 21 out of bounds for length 5
As you can see, the statement:
list[21] = “Jack”
Caused the program to crash because we’re accessing the index number 21 while the array has only a size of 5 elements.
Kotlin Print Array: How to Print an Array in Kotlin
There are multiple ways to print the elements of an array from the output stream. But perhaps the easiest way is to use the for
loop and set the target array as the collection of the loop. In the section below, we’ve explained how to do that.
Kotlin Array and for Loop
We can set the name of an array as the collection of a for loop in Kotlin, and then the loop will iterate through the elements of the array and so we get the access to the elements of that array then.
Example: using for loop to iterate an Array
fun main(){ var list = arrayOf<Any>("Omid","Jack","Ellen", "Peter","Elon", false, true) for (element in list){ println(element) } }
Output:
Omid Jack Ellen Peter Elon false true
Kotlin Array: Check for Elements in Arrays:
If you want to see if an array has a specific element in it or not, you can use the in
operator.
This is the syntax of how to use the in operator:
if (value in array_name){ #instructions... }
Here the value
is the element we want to check the target array for to see if the array has it or not.
array_name
this is the array we want to search it for the target element.
Basically, using the in
operator, we can create a conditional statement that either returns a value true or false. If the element was in the target array, the return value of this condition becomes true, otherwise, the value false will return as a result.
Note that if statement is not the only place to use the in
operator, though!
For example, you can simply call this operator on the right side of the assignment operator and a variable on its left side so that the variable will get the result of the operation:
var variable_name = value in arar_name
Example: checking for an element in an Array
fun main(){ var list = arrayOf<Any>("Omid","Jack","Ellen", "Peter","Elon", false, true) if ("Ellen" in list){ println("Yes, the value Ellen is in the list") }else{ println("No, the value Ellen is not in the list") } }
Output:
Yes, the value Ellen is in the list