Declaring a Variable

Imagine you are writing an adventure game that assigns players quests to embark on. These quests should scale in difficulty as the player grows stronger and progresses through the game. You will likely want a variable for keeping track of the player’s game progress.

In Main.kt, create your first variable, called playerLevel, and assign it a value:

Listing 2.1  Declaring a playerLevel variable (Main.kt)

fun main() {
    println("Hello, world!")
    var playerLevel: Int = 4
    println(playerLevel)
}

Here, you have assigned an instance of the type Int to a variable called playerLevel. Let’s walk through each part of the code.

You defined a variable using the keyword var, which indicates that you want to declare ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.