Kotlin Arrays

An array in Kotlin is none other than a Kotlin variable that can be declared by the statement val or var, and the class arrayOf, while specifying the type String, int, float ...

 1 - One-dimensional table 

 A one-dimensional array is declared using the statement:

var (or val) array_name < type> = arrayOf (element1, element2, ...)

Example (String array)

var myTab = arrayOf < String> ("Laptop", "Tablet", "Iphone")

Example (Array type int)

var myTab = arrayOf < int> (11, 23,7,3)

Access an element of the table To access an element at the ith position of a Kotlin array, we proceed in the same way as in java: Example

var myTab = arrayOf < String> ("Laptop", "Tablet", "Iphone")
println (myTab [0]) // show "Laptop"

Browse all elements of a table To browse all the elements of a Kotlin array, we use the for loop:

for (str in Table)
  println (str)


fun main (args: Array < String>) {
  val myTab = arrayOf < String> ("age", "size", "weight", "address")
  for (str in myTab)
  println (str)

2 - Multidimensional array 

 A multidimensional array is nothing but a table whose components are themselves arrays. To understand this we will treat this on a simple example: Example

fun main (args: Array < String>) {
// define an array of String type
 val myTab1 = arrayOf < String> ("Laptop", "Iphone", "Tablet")
// define an array of String type
 val myTab2 = arrayOf < String> ("New", "Price")
// define an array of arrays
 val myTab = arrayOf (myTab1, myTab2)
// show the 2nd element of the first array
println (myTab [0] [1]) // show Iphone

Leave a Reply