Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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)
}
lateinit var day : String

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

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)
}
Conflicting declarations: var day: String, var day: String
Conflicting declarations: var day: String, var day: String
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.

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()
}
The first day of the weekend is Saturday
Non-working days are Saturday and Sunday
The first day of the weekend is Saturday

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.

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
}
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)
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)
In week number 51, you have saved $342.
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
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Instruction 2