Start learning free

LESSON 9 OF 348 · VARIABLES

The Power of Variables in Kotlin: One Change, Whole Program

Lesson Read the full explanation

Now that we've learned about variables, let's see why they are so important in our prgrammers' life:

Consider this simple program wich prints a story:

println("My name is John and I am 40 years old")
println("Coding at age 40 is really fun")
println("My son is named after me, John")
println("I'd love him to be as cool as me at age 40")
println("It's so funny when my wife calls John we both respond")

Changing the story:

This is a perfectly working program. But what if I come back to it and want to change the character's name to Andy and his age to 32?

Well, I'm going to have to go through the entire program and manually change the name John to the name Andy and the age 40 to the age 32:

println("My name is Andy and I am 32 years old")
println("Coding at age 32 is really fun")
println("My son is named after me, Andy")
println("I'd love him to be as cool as me at age 32")
println("It's so funny when my wife calls Andy, we both respond")

This is not horrible as I had to go through only 5 lines of code. But what if my code consisted of hundreds of lines?

It's a disaster. Going through the whole code and manually changing the name and age is boring but more importantly it's super easy to make mistakes.


The story with variables:

This is where variables shine. If I used a variable to store the name of the character and another variable to store his age when I first wrote this code, it would have looked like this:

val name = "John"
val age = 40

println("My name is $name and I am $age years old")
println("Coding at age $age is really fun")
println("My son is named after me, $name")
println("I'd love him to be as cool as me at age $age")
println("It's so funny when my wife calls $name we both respond")

Changing the story with variables:

Now whenever I want to change the character's name and age, I only have to change two lines of code, instead of possibly hundreds.

If I want my character to be named Andy and aged 32, I initialize the variables name with Andy and age with 32 and leave the rest of the code untouched:

val name = "Andy"
val age = 32

println("My name is $name and I am $age years old")
println("Coding at age $age is really fun")
println("My son is named after me, $name")
println("I'd love him to be as cool as me at age $age")
println("It's so funny when my wife calls $name we both respond")

Assignment
Follow the Coding Tutorial and let's witness the power of variables!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · VARIABLES

    The Power Of Variables in Kotlin, explained

    The problem with repeating values

    Imagine a program that tells a short story about a character called John who is 40 years old. Without variables, every line spells the values out:

    println("My name is John and I am 40 years old")
    println("Coding at age 40 is really fun")
    println("My son is named after me, John")
    println("I'd love him to be as cool as me at age 40")
    println("It's so funny when my wife calls John we both respond")
    

    This works. The trouble starts when the character becomes Andy, aged 32. You have to find every John and every 40 and replace them by hand. In five lines that's easy. In five hundred lines it's tedious, and it is easy to miss one. A program that says Andy in four places and John in a fifth is a bug, even though it compiles and runs.

    A blind search-and-replace is not a safe fix either. Replacing every 40 would also change an unrelated 40 elsewhere in the program, such as a price or a score.

    Naming the value once

    A variable gives a value a name, so the value is written in one place and used by name everywhere else:

    val name = "John"
    val age = 40
    
    println("My name is $name and I am $age years old")
    println("Coding at age $age is really fun")
    println("My son is named after me, $name")
    println("I'd love him to be as cool as me at age $age")
    println("It's so funny when my wife calls $name we both respond")
    

    Inside a string, $name is a string template: Kotlin replaces it with the variable's value when the line runs. To use something longer than a name, such as a calculation, wrap it in braces: "next year: ${age + 1}". To print a literal dollar sign, write \$.

    Now the story changes with two edits:

    val name = "Andy"
    val age = 32
    

    Every println line stays exactly as it was, and all five lines update. The value lives in one place, so it can't be half-changed.

    Why this matters beyond the example

    • One edit instead of many. Change the definition and every use follows.
    • Fewer mistakes. There is no second copy that can fall out of sync.
    • Readable code. $age says what the number means. A bare 40 in the middle of a line doesn't.
    • Programs that adapt. A variable's value can come from somewhere else later: user input, a file, a calculation. The lines that use it don't need to change.

    The exercise

    The starter code already has the story line and two variables with the wrong values:

    // Create variables here:
    var experience = 5
    var language = "Python"
    
    
    // Print story here:
    println("I have $experience years of experience with $language")
    

    The task is to turn it into a story about 13 years of experience in Java, without touching the println line. Only the values to the right of each = change. The names, var and the equals sign stay put:

    // Create variables here:
    var experience = 13
    var language = "Java"
    
    // Print story here:
    println("I have $experience years of experience with $language")
    

    It prints:

    I have 13 years of experience with Java
    

    Two edits changed the whole output. That's the point of the lesson.

    Variables that change while the program runs

    The story variables are set once, but a variable declared with var can also be given a new value later, and every use after that sees the new value:

    var years = 5
    println("I have $years years")
    years = 6
    println("I have $years years")
    
    I have 5 years
    I have 6 years
    

    The text of the println line is identical both times. Only the value behind $years differs. This is the same idea as editing the top of the story, but happening while the program runs.

    Details worth knowing

    • Types are inferred. Nothing here says Int or String. Kotlin sees 13 and decides experience is an Int, and sees "Java" and decides language is a String. Each variable keeps that type: assigning text to experience later would be a compile error.
    • var versus val. The exercise uses var, which allows the value to be reassigned later. In the story above, the values never change after they are set, so val is the better choice there. The difference gets its own lesson.
    • Names must match. The template $experience needs a variable called exactly experience. A misspelling gives an unresolved reference, and the program does not compile.
    • Quotes belong to the value. The text value needs quotes, "Java". The number does not, 13.

    Key takeaways

    • Writing a value in many places makes changes slow and error-prone.
    • A variable stores the value once, under a name.
    • $name inside a string inserts the variable's value; ${...} inserts the result of an expression.
    • To change the program's output, change the variable's value and leave the code that uses it alone.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free