Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

KotlinArrays


Kotlin Arrays

Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value.

To create an array, use thearrayOf() function, and place the values in a comma-separated list inside it:

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

Access the Elements of an Array

You can access an array element by referring to theindex number, insidesquare brackets.

In this example, we access the value of the first element in cars:

Example

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")println(cars[0])// Outputs Volvo
Try it Yourself »

Note: Just like with Strings, Array indexes start with 0: [0] is the first element. [1] is the second element, etc.


Change an Array Element

To change the value of a specific element, refer to the index number:

Example

cars[0] = "Opel"

Example

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// Now outputs Opel instead of Volvo
Try it Yourself »

Array Length / Size

To find out how many elements an array have, use thesize property:

Example

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")println(cars.size)// Outputs 4
Try it Yourself »


Check if an Element Exists

You can use thein operator to check if an element exists in an array:

Example

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")if ("Volvo" in cars) {  println("It exists!")} else {  println("It does not exist.")}
Try it Yourself »

Loop Through an Array

Often when you work with arrays, you need to loop through all of the elements.

You can loop through the array elements with thefor loop, which you will learn even more about in the next chapter.

The following example outputs all elements in thecars array:

Example

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")for (x in cars) {  println(x)}
Try it Yourself »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp