How to initialize an array in Kotlin with values?

AndroidMobile DevelopmentApps/ApplicationsKotlin

An array is a type of data structure that contains a definite number of similar types of values or data. In this data structure, every element can be accessed using the array index that usually starts at "0".

In Kotlin, arrays can be created using the function arrayOf() or using an Array constructor.

Important points regarding Arrays in Kotlin −

  • Arrays are stored in a sequence as per the memory location is concerned.

  • All the elements in an array can be accessed using their index.

  • Arrays are mutable in nature.

  • In conventional programming, the size usually declared along with its initialization, hence we can conclude that their size is fixed.

Example

In this example, we will declare an Array of subjects and we will print the values.

fun main()
{
   // Declaring an array using arrayOf()
   val sampleArray= arrayOf("Java","C", "C++","C#", "Kotlin")

   // Printing all the values in the array
   for (i in 0..sampleArray.size-1)
   {

      // All the element can be accessed via the index
      println("The Subject Name is--->"+sampleArray[i])
   }
}

Output

It will generate the following output −

The Subject Name is--->Java
The Subject Name is--->C
The Subject Name is--->C++
The Subject Name is--->C#
The Subject Name is--->Kotlin

Example – using Array constructor

In Kotlin, arrays can be declared using an array constructor as well. This constructor will take two arguments; one is the size of the array and the other is a function that accepts the index of an element and returns the initial value of that element.

In this example, we will see how we can use the built-in feature of array constructor to populate an array and use the same value further in the application.

Example

fun main()
{

   // Declaring an array using arrayOf()
   val sampleArray= arrayOf("Java","C", "C++","C#", "Kotlin")

   // Printing all the values in the array
   for (i in 0..sampleArray.size-1)
   {

      // All the element can be accesed via the index
      println("The Subject Name is--->"+sampleArray[i])
   }

   // Using Array constructor
   val myArray = Array(5, { i -> i * 1 })
   for (i in 0..myArray.size-1)
   {
      println(myArray[i])
   }
}

Output

It will generate the following output −

The Subject Name is--->Java
The Subject Name is--->C
The Subject Name is--->C++
The Subject Name is--->C#
The Subject Name is--->Kotlin
0
1
2
3
4
raja
Updated on 27-Oct-2021 09:00:20

Advertisements