Instruction 2

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

Mutable and Immutable Variables

In Kotlin, variables can be mutable or immutable. There are instances where a variable’s data will never change throughout the program. In such cases, you have to declare your variable with val. On the other hand, if the data in the variable can change, use var.

fun main(args: Array<String>) {
 val weeklyInterest = 100

 // Rest of the code
}
val totalWeeklyAmount = mondayAmount + tuesdayAmount + wednesdayAmount + thursdayAmount + fridayAmount
totalWeeklyAmount = totalWeeklyAmount + weeklyInterest

Using const variables

const is another Kotlin keyword used to indicate a variable that can’t be changed. The difference between const and val is that const variables are only allowed on top-level, named objects or companion objects. For a variable to be at such high scopes, it means it has to be accessible throughout the whole file and not in the function. Same as the val, any attempt to alter a const variable will result in an error.

const val WEEKLY_INTEREST = 100

fun main(args: Array<String>) {

  // ...

  totalWeeklyAmount = totalWeeklyAmount + WEEKLY_INTEREST

  // Rest of code
}
See forum comments
Download course materials from Github
Previous: Instruction 1 Next: Instruction 3