In Kotlin, the size
property determines the number of elements within a collection. It is not only applicable to lists but also to other collections that we’ll be working with in the coming lessons.
Similarly to the length
property for Strings, size
counts the number of elements in a collection and returns an Integer value.
Take a look at the following list of major European rivers:
val majorRivers = listOf("Volga", "Danube", "Loire", "Rhine", "Elbe")
We can append size
to majorRivers
and retrieve the number of elements in the list:
println(majorRivers.size) // Prints: 5
Additionally, this code can be used to construct an informative String about our list:
println("There are ${majorRivers.size} major rivers in Europe.") // Prints: There are 5 major rivers in Europe.
Furthermore, size
can be used along with an element’s index to retrieve the last element of a collection:
println(majorRivers[majorRivers.size - 1]) // Prints: Elbe
- Within the brackets,
majorRivers.size
equates to5
. Subtracting1
from this value results in4
which becomes the final numerical index within the brackets. majorRivers[4]
returns the 4th and last element in the list,"Elbe"
.
This strategy is most commonly used when iterating over a collection or simply grabbing the last element of a list when we don’t know how many list elements there are in total. We’ll learn more about how to iterate over a collection later in the course.
Instructions
In Fruit.kt, create a variable, fruitTrees
, which stores a mutable list of the following fruit trees:
"Apple"
"Plum"
"Pear"
"Cherry"
On the next line, construct the following sentence using String template syntax:
I am growing [___] different types of fruit in my garden.
Replace the value within the brackets with fruitTrees.size
. Use a print statement to output this sentence to the screen.