Arrays in Kotlin: A Comprehensive Guide With Examples

In Kotlin, an Array stores a collection of elements of the same types. Array stores elements in contiguous memory locations, like each element is stored in a sequential memory address though each element place next to another. Arrays in Kotlin are Statically typed so the type of element stored in an array is determined at once when the array is created and its nonchangeable. Array are fixed size, meaning once we create an array with elements then its size cannot be changed. We can modify its elements but adding and removing elements is restricted. So basically we can use an array whenever we know how many elements we are going to store in a fixed number.

Arrays in Kotlin: A Comprehensive Guide With Examples

Arrays in Kotlin

Creating an Array in Kotlin:

1. Using arrayOf() method.

2. Using intArrayOf() method.

  • Updating integer array elements.
  • Output

3. To create a double-type array we will use doubleArrayOf() function.

  • Modifying or Updating double array elements.
  • Output:

4. To create a String array we will be using arrayOf() method.

  • Updating String array elements.
  • Output:

Creating an empty array with default value:

Array Iterating(Printing array elements):

There are 3 ways to print or get array elements in Kotlin.

  1. Using Index Position – To print single element only.
  2. Using for loop – To print complete array.
  3. Using for each loop – to print the complete array.

There are a ton of array inbuilt methods available for Kotlin. You can read them from HERE on Kotlin’s official page. In our next article, we will be covering all of them. Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *