Variables

A variable is an identifier for a memory location that holds a value. A simpler way to describe a variable is an identifier that holds a value. Consider the following program:

fun main(args: Array<String>) {
var x: Int = 1
}

The preceding x is a variable and the value it holds is 1. More specifically, x is an integer variable. The x is referred to as an integer variable because x has been defined to have the Int data type. As such, the x variable can only hold an integer value. To be more accurate, we say that x is an instance of the Int class. At this point, you must be wondering what the words instance and class mean in this context. All will be revealed in due time. For now, let's focus on the topic of variables.

When defining a variable in Kotlin, we make use of the var keyword. This keyword specifies that the variable is mutable in nature. Thus, it can be changed. The data type of the declared variable comes after a semicolon that follows the variable's identifier. It is important to note that the data type of a variable need not be explicitly defined. This is because Kotlin supports type inference—the ability to infer types of objects upon definition. We might as well have written the definition of our x variable as:

var x = 1

The outcome of the definition would be the same. A semicolon can be added to the end of the line of our variable definition but, similar to languages like JavaScript, it is not required:

var x = 1 // I am a variable identified by x and I hold a value of 1
var y = 2 // I am a variable identified by y and I hold a value of 2
var z: Int = x + y // I am a variable identified by z and I hold a value of 3

If we don't want the values of our variables to change over the course of the execution of our program, we can do so by making them immutable. Immutable variables are defined with the val keyword, as follows:

val x = 200
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.229