Welcome, future coder! Today, we'll explore a fundamental concept: Arrays. Picture a train; each car represents an element, together comprising an Array. We'll dive deep into Arrays, discovering how to create, access, and work with their properties. So, are we ready to embark on this journey?
Visualize a roller coaster queue — each individual represents an element of an Array, and their position corresponds to an index beginning from zero. An Array is, therefore, a sequence of elements easily accessible via integer indices. Pretty nifty, right?
In Kotlin, we use the arrayOf() function to create Arrays, akin to assigning passengers to a train's compartments. Let's fill our train with friends:
Below, we've created an array named friends, consisting of three elements: "John", "Lisa", and "Sam", which we then printed using the joinToString() utility. The joinToString() merges an array or collection into a single string, separating each item with a comma, thus simplifying the display or printout of collections in a neat format.
Next, let's retrieve our first friend from the friends Array using an index:
We'll print "John", the first (0th) element. However, do be careful: accessing an invalid index like friends[5] will result in an error.
Kotlin offers built-in properties for Arrays. size returns the count of elements, indices provides the valid index range, and lastIndex denotes the last element's index:
Our friends Array has a size of 3, indices ranging from 0..2, and a lastIndex value of 2.
