Cody Engel

Software Engineer at ActiveCampaign

Let’s Learn How To Code Using Kotlin — Part 004

Wow, can you believe we are already on our fifth installment of this series? If you are new to this series I strongly recommend going back to the introduction as each part builds off of the previous parts. In part four we are going to continue learning about control flows by learning about the other loops in Kotlin. However before we get started make sure you create a new package named part_004 and create a new Kotlin file named app. Awesome, let’s get started.

Thanks Onur Sahin over on Unsplash

In this example we are going to print out a list of cars using three different approaches. In order to get a list of cars searched for “best sports cars 2017” and found this article over on Car and Driver. Feel free to either steal my list or come up with your own. Our first step in creating this program is by creating an array of String objects. For my program it looks like this:

val cars = arrayOf(
        "Toyota Camry",
        "Toyota Corolla",
        "Honda Civic",
        "Nissan Altima",
        "Honda Accord",
        "Hyundai Elantra",
        "Nissan Sentra",
        "Ford Fusion",
        "Chevrolet Cruze",
        "Hyundai Sonata",
        "Ford Focus",
        "Mazda MX-5 Miata",
        "Fiat 124 Spider",
        "Subaru BRZ",
        "Toyota 86",
        "Nissan Z",
        "Dodge Challenger",
        "Ford Mustang",
        "Chevrolet Camaro",
        "Audi TT / TTS"
)

You might be wondering right now what arrayOf is or even what an array is. To answer the first question, arrayOf lets you create an array of objects, in this case they are strings. To answer the second question an array is a collection of objects. That collection will typically have some commonality, in this case we want to represent a list of car names. It’s also probably important to note that each item is separated by a comma , with the new line being optional (but it can help with readability of longer arrays).

As we get further into this series we’ll discuss other types of collections along with the pros and cons of them. In general an array is the most basic type of a collection and serves as a building blocks of several others. While this may fall into “Too Much Information Cody!” I also want to point out that arrays of things are generally how apps work. Your Facebook wall is powered by an array of Posts, Medium is powered by an array of Articles, and YouTube is powered by an array of Videos. These aren’t the exact implementations, and are instead simplified examples.

With that out of the way, let’s start printing out these cars.

The Basic For Loop

So now it’s time to iterate over this list of cars and do something with them. In our first example we’re simply going to print out the cars, one car per line. Here’s our first example:

println("\nPrinting Cars In Order")
for (index in cars.indices) {
    println(cars[index])
}

So this is technically not the most basic for loop, instead I wanted to give an example of you might do this in Java (or other languages). Essentially what we are doing is getting an array of indexes (which are integers) with cars.indices, and we are iterating over that list. What this allows us to do is access the array by its index. If I wanted to only access Toyota Camry I would simply reference cars[0] which is the index of that car. With arrays they always start at zero, and so if I wanted to access Toyota Corolla which is the 2nd item in the list I’d reference cars[1]. Our loop above will start out at zero and end at nineteen (our list has twenty items).

Performing Operations On The Cars

The next example I want to give is how we would perform operations on these cars. The easiest example I can think of is printing out the car names in lowercase letters. In doing so we are also going to access the cars directly, so no more index. In general this is how you probably should iterate over items in a list in Kotlin. Here’s what that looks like:

println("\nPrinting Cars In Order (Lowercase)")
for (car in cars) {
    println(car.toLowerCase())
}

So essentially what we are doing is taking our values in cars and setting each one to a variable named car. We are then going to take the value of car, make it lowercase, and then print it out.

Stop Printing After “Ford” Is Printed

The last example I want to go through is using a while loop to only print out items until we reach one that has “Ford” in the name. Here is what my solution looks like:

println("\nPrinting Cars Until Ford Found")
var fordWasPrinted = false
var index = 0;
while (!fordWasPrinted) {
    val car = cars[index]
    println(car)
    fordWasPrinted = car.toLowerCase().contains("ford")
    index++
}

Before we get to the while loop we first setup two variables. We need a condition to keep track of for our loop, for that we declare fordWasPrinted which by default is false. I also define index which will keep track of where we are in our array, again, arrays start out at zero.

Now it’s time to enter into the while loop, as long as fordWasPrinted is false it will keep going through the loop. The first thing we do inside of the loop is set car equal to our current item in the cars array. We then print out the car to the console. On the next line we determine if the car contains the word “ford”. We do that by first getting a lowercase string representation of car and then ask if it contains the word “ford”. If it does then it will return true, otherwise it will return false. We are assigning that returned value to fordWasPrinted. Then we increment the value of index and we return to the top of our loop where we check the value of fordWasPrinted. Once that value is true we will exit the loop and complete our program.

As a note, if you don’t have Ford in the list, my solution will cause the app to crash. As homework feel free to add some error handling so that the app won’t crash if you omit Ford from the list.

So now you can go ahead and run the program and should see that the car list is printed out three times, and each time it should be slightly different. The first time it will just print them out normally, the second time they will be all lowercase, and the third time it will only print out part of the list. Here’s my full solution:

fun main(args : Array<String>) {

    val cars = arrayOf(
            "Toyota Camry",
            "Toyota Corolla",
            "Honda Civic",
            "Nissan Altima",
            "Honda Accord",
            "Hyundai Elantra",
            "Nissan Sentra",
            "Ford Fusion",
            "Chevrolet Cruze",
            "Hyundai Sonata",
            "Ford Focus",
            "Mazda MX-5 Miata",
            "Fiat 124 Spider",
            "Subaru BRZ",
            "Toyota 86",
            "Nissan Z",
            "Dodge Challenger",
            "Ford Mustang",
            "Chevrolet Camaro",
            "Audi TT / TTS"
    )

    println("\nPrinting Cars In Order")
    for (index in cars.indices) {
        println(cars[index])
    }

    println("\nPrinting Cars In Order (Lowercase)")
    for (car in cars) {
        println(car.toLowerCase())
    }

    println("\nPrinting Cars Until Ford Found")
    var fordWasPrinted = false
    var index = 0;
    while (!fordWasPrinted) {
        val car = cars[index]
        println(car)
        fordWasPrinted = car.toLowerCase().contains("ford")
        index++
    }

}

And that’s all for this lesson. As always if you have any questions or comments feel free to leave a response below. The subject of this article was inspired by a response in the previous article, so I do my best to incorporate feedback in future articles.

More by Cody Engel

More Related Stories