kotlin add element to array
To add an element to an array in Kotlin, you can follow these steps:
Declare an array: Start by declaring an array variable and assigning it an initial set of elements. For example, you can declare an array of integers like this:
kotlin val numbers = arrayOf(1, 2, 3, 4, 5)
Create a new array with the added element: Since arrays in Kotlin have a fixed size, you cannot directly add elements to them. Instead, you need to create a new array with the desired element added. You can do this using the
plus()
function or the+
operator. For example, to add the number 6 to thenumbers
array, you can use either of these approaches:Using the
plus()
function:kotlin val newNumbers = numbers.plus(6)
Using the
+
operator:kotlin val newNumbers = numbers + 6
Both approaches create a new array
newNumbers
that contains all the elements from the originalnumbers
array plus the additional element.Access the new array: You can now access the new array
newNumbers
and perform operations on it. For example, you can print the elements of the array using a loop:kotlin for (number in newNumbers) { println(number) }
This will output:
1 2 3 4 5 6
By following these steps, you can add an element to an array in Kotlin. Remember that arrays in Kotlin are immutable, so each time you add an element, a new array is created with the additional element.