MOCKSTACKS
EN
Questions And Answers

More Tutorials








Kotlin Array declaration access change

An array is a homogeneous data structure, that stores a sequence of consecutively numbered values--allocated in contiguous memory. Each object of the array can be accessed by using its number (i.e., index).

In Kotlin to create an array we use the built in function arrayOf() and we place values inside parentheses with comma separated format.

In this section you will learn:


Kotlin Array declaration syntax

val array_name = arrayOf("element1", "element2", "element3" ...)

Access the Elements of an Array

To access an element in an Array we will need to use the index of that element for example: array_name[1] in this example we access element at index 1 for array arra_name, we use braces to surround the index.

fun main() {
  val fruits = arrayOf("Orange", "Banana")
  println(fruits[0])
}

Output

Orange


Change an Array Element in Kotlin

to change an array element we just need to use the existing index and set a new value. See below example :

fun main() {
  val fruits = arrayOf("Orange", "Banana")
  fruits[0] = "Apple"
  println(fruits[0])
}

Output

Apple


Kotlin Array Length / Size

In Kotlin we use function size to get the length and number of elements in an array. See example below:

fun main() {
  val fruits = arrayOf("Orange", "Banana")
  println(fruits.size)
}

Output

2


Kotlin Check if an Element Exists

in Kotlin the operator in is used to identify if an element exist in array and it will return true if exist and false if not. See example below:

fun main() {
  val fruits = arrayOf("Orange", "Banana")
  if ("Banana" in fruits) {
  	println("It exists!")
  } else {
    println("It does not exist.")
  }
}

Output

It exists!

Conclusion

In this page (written and validated by ) you learned about Kotlin Array declare access change size find . What's Next? If you are interested in completing Kotlin tutorial, your next topic will be learning about: Kotlin Array Sorting .



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.