valkeyword declares a read only variables. Use this if you know the value of the variable won’t change in the future (constants)
Implicit vs. Explicit variable declaration
Implicit variable declaration: You do not need to specify the variable type
var x = 25.0 // Kotlin compiler will guess that this is a "double"
Explicit variable declaration: You must specify the variable type
var x:Double = 25.0 // Kotlin does NOT guess becuase you told it x should be a double
Working with Mutable Lists
A mutable list is a dynamically sized array. This means that the size of the array is programatically calculated based on the number of items in the array.
Creating an empty array:
mutableListOf() → creates an empty list. Kotlin will “guess” what type of data the list contains based on either your 1) explicit variable declaration; or 2) whatever items you put in the list
mutableListOf<String>() → creates an empty list of the specified type (In this example, list of strings)
Initializing the array with items
mutableListOf(”Apple”, “Banana”, “Carrot”) → You did not specify what type of items should be in the list. But “Apple”, “banana” and “Carrot” all look like strings, so Kotlin will assume this is a list of strings.
mutableListOf<Int>(100, 80, “abcd”, 99)
You also specify that the initial items in the list are 100, 80, “abcd” and 99
By using the <Int> keyword, you specified that the list should contain integer values.
Therefore, Kotlin will check that your initial items are indeed Integers.
In this example “abcd” is a string, not an integer. So Kotlin will show an error and prevent you from proceeding!
Functions for manipulating the array
.size → returns the total number of items in the array
.get(pos) → returns the item at the specified position
.set(pos, newValue) → updates the item at the specified position with the new value
.removeAt(pos) → removes the item at the specified position
.add(item) → adds the item to the end of the list
Looping through the array
val myList:MutableList<Int> = mutableListOf(99, 100, 50, 4000)
for (currItem in myList) {
println(currItem)
}
Example 2: Looping, but having access to the current position of the item
Use the .withIndex() function
val myList:MutableList<Int> = mutableListOf(99, 100, 50, 4000)
for ((i, currentItem) in myList.withIndex()) {
println("Item in position ${i} is ${currItem}")
}
Searching the array
Example 1: Searching for an item
val myList:MutableList<Int> = mutableListOf("Bob", "Mary", "Lemon", "Alex", "Sarah")