Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tasks

Make sure you do all of these. They won’t take very long.

Important

After you’ve finished, remember to commit your work and push it to GitHub!

You should commit regularly, using informative commit messages. You should push at least once, at the end of every work session.

Task 2.5.1

  1. In the tasks/task2_5_1 subdirectory of your repository, write a Kotlin program containing four lines of code. The first line should create a val variable and assign an integer value to it. The second line should print the value of the variable. The third line should attempt to assign a new value to the variable. The fourth line should attempt to print the value of the variable again.

  2. Try compiling this program so that you understand exactly how the compiler reacts to the error on the third line.

  3. Fix the error by changing val to var, then recompile and run the program.

Task 2.5.2

  1. In the tasks/task2_5_2 subdirectory of your repository, write a Kotlin program containing these lines of code:

    val myAge = 29u
    val universeAge = 13_800_000_000L
    val status = 'M'
    val name = "Sarah"
    val height = 1.78f
    val root2 = Math.sqrt(2.0)
    

    Check that your program compiles. Then see if you can predict the type of each of these variables. Make a note of your predictions.

  2. To check whether you have predicted the type of variable myAge correctly, add the following print statement to the program:

    println(myAge::class)
    

    Add a similar print statement for each of the other variables. Then compile and run the program. How many of your predictions were correct?