Instruction 1

Variables

A variable is a named storage location for data. You can store any type of data in a variable. In programming terms, you assign data to variables. Once you assign data to a variable, the variable holds the value of the assigned data. The syntax for declaring variables in Kotlin is straightforward. Open a Kotlin Playground session in your browser. Go to https://play.kotlinlang.org and create a variable called day using the following:

fun main() {
  var day = "Monday"
  println(day)
}

var is a keyword in Kotlin for defining variables. day is the name of the variable. Monday is the data contained in the variable.

Having done this, you can use day anywhere in your program where you want to imply Monday. Until day is assigned a different value, it remains Monday throughout your program.

You may initialize a variable without assigning data by introducing lateinit. Declare a lateinit above the main function and assign a value to it as before:

lateinit var day : String

fun main(args: Array<String>) {
  day = "Monday"
  println(day)
}

Note: Make sure you assign a value to the variable before using it. Otherwise, you’ll get a runtime error.

Naming Variables

Always choose clear names for your variables. It’s good practice to name your variables in a simple, self-explanatory manner. In the above example, you can see that the variable’s name gives an idea of the value it contains. By convention, you should name your variables using the lower camel case format. They must begin with letters and include numbers afterward if desired. No other characters are allowed.

Updating Variables

After initially assigning a value to a variable, you have to omit the keyword if you want to update the variable. Otherwise, you’d be re-initializing a variable with the same name, and that’s not allowed. Return to the original example and add a second var, again named day.

fun main() {
  var day = "Monday"
  var day = "Tuesday" // Not allowed
  println(day)
}

This results in an error as seen below:

Conflicting declarations: var day: String, var day: String
Conflicting declarations: var day: String, var day: String

Instead, omit the var keyword to update the value of day:

fun main() {
  var day = "Monday"
  day = "Tuesday" // OK
  println(day)
}

Variable Scopes

The context within which a variable is defined is the scope of the variable. They are top-level, class and function scopes in descending order. A top-level variable is available at the same level as the main function or any other top-level class or function in your program.

Note that the main function is a top-level function. Any other variable, function, or class defined on the same level as main has a top-level scope. Update your code to create a top-level variable and access it in another top-level function, class or a local function of the class:

const val FIRST_DAY_OF_THE_WEEKEND = "Saturday" // Top-level variable declaration

class ClassLevel {
 val nonWorkingDays = FIRST_DAY_OF_THE_WEEKEND + " and " +  "Sunday" // Accessing a top-level variable within a class

 fun display(){
   println("Non-working days are " + nonWorkingDays) // Accessing a top-level variable within a function in a class
   println("The first day of the weekend is " + FIRST_DAY_OF_THE_WEEKEND) // Accessing a top-level variable within a function in a class
 }
}

fun main(args: Array<String>) {
 println("The first day of the weekend is " + FIRST_DAY_OF_THE_WEEKEND) // Accessing a top-level variable in a top-level function
 val a = ClassLevel()
 a.display()
}

Run the code. Your output will display:

The first day of the weekend is Saturday
Non-working days are Saturday and Sunday
The first day of the weekend is Saturday

Note: val is also a keyword for defining variables. When used in place of var, it makes the variable read-only. More on this in the next segment.

Note: Scopes are accessible upwards. Top-level scopes can’t access class-level or function scopes. Likewise, class-level scopes can’t access function-level scopes. But the reverse is possible.

Using Variables

Write a program that accepts a list of numbers representing daily savings contributions. You’ll supply the daily contributions with program arguments. The program should calculate the total amount and return the total. It will also return the week number in the year.

Enter the following values separated by a space as Kotlin Playground program arguments:

15 25 12 40 250

This represents the amount saved for each day of the working week in your currency. They’re ordered from Monday to Friday. In your program, these amounts will be available in the args argument of the main function. Extract and assign them to variables using the following code:

import java.util.Calendar

fun main(args: Array<String>) {
 val mondayAmount = args[0].toInt()
 val tuesdayAmount = args[1].toInt()
 val wednesdayAmount = args[2].toInt()
 val thursdayAmount = args[3].toInt()
 val fridayAmount = args[4].toInt()
 val totalWeeklyAmount = mondayAmount + tuesdayAmount + wednesdayAmount + thursdayAmount + fridayAmount

 val weekNumber = getWeekNumber()
 println("In week number $weekNumber, you have saved $$totalWeeklyAmount.")
}

fun getWeekNumber(): Int {
 val calendar: Calendar = Calendar.getInstance()
 val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
 return weekOfYear
}

Note: args[0] accesses the first item in the program arguments, followed by args[1] and so on. You’ll learn more about arrays and other collections later in this course.

Make sure to provide at least five whole numbers. These numbers represent your program arguments. Otherwise, your program will crash since the code expects five different integer arguments. The error looks like the following if there are no arguments at all:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
 at java.lang.NumberFormatException.forInputString (:-1)
 at java.lang.Integer.parseInt (:-1)
 at java.lang.Integer.parseInt (:-1)

Or like below if the arguments are not at least 5:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
 at FileKt.main (File.kt:8)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1)

Run the program and take a look at the output in the console. Your week number will change depending on the date you run the code and it’ll look something like this:

In week number 51, you have saved $342.

You’ve made use of variables to keep track of the amount saved for each working day. Whenever your program runs, the variable values will be the amounts you save for that week. This is powerful in that it makes your program dynamic. If you didn’t use variables, you’d have to hardcode the amounts each time your program runs. It’d look something like this:

import java.util.Calendar

fun main(args: Array<String>) {

 val totalWeeklyAmount = 15 + 25 + 12 + 40 + 250

 val weekNumber = getWeekNumber()
 println("In week number ${weekNumber}, you saved $${15 + 25 + 12 + 40 + 250}")
}

// A function that returns the current week number in the year.
fun getWeekNumber(): Int {
   val calendar: Calendar = Calendar.getInstance()
   val weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR)
   return weekOfYear
}

While this works, it’s difficult to understand and far from being scalable or re-usable. To re-use the individual values, you have to copy them, repeating yourself, and copying code is prone to simple copying errors.

Note: Don’t Repeat Yourself (DRY) is an important concept in software development. Any time you find yourself repeating code, put the code in a function or a single place for access.

Variables make your program dynamic, clean, and easy to read and reason about. You may have realized that the variables are aptly named. This makes everyone looking at your code immediately understand each variable’s data.

There’s more when it comes to variables in Kotlin. Read on to see the different types of variables in Kotlin.

See forum comments
Download course materials from Github
Previous: Introduction Next: Instruction 2