In this tutorial, you will learn about kotlin variables. You will learn how to declare and define kotlin variables. We will also go through different examples to show different scenario created while using kotlin variables.
As you know very well, a kotlin variable is name given to memory location so that we can manipulate the data within it in a program i.e. A variable allow to assign value in it that can be modified at different points of time when program runs, as long as they are within the scope in which it is defined. For example,
var x = 10 x = 16
Here, x is a variable whose value is 10. In the next line, we changed the value to 16. Now, x holds the value 16.
Each kotlin variable has a specific data type that determines the size and layout of the variable’s memory. It also decides the range of the values that can be stored within that memory. It also decides the set of operations that can be applied to the variable.
The name of the kotlin variables can be composed of letters, digits and the underscore character. We will go through this later in this post.
How to declare a Variable in Kotlin?
To declare a kotlin variable, either var or val keyword is used. For example,
– Variable using val Keyword
val marks = 40;
– Variable using var Keyword
var name = "Rahul Kumar";
We will soon see the difference between val and var later in this post.
Here, name is variable of data type String and marks is variable of type Int. In Kotlin, you do not need to specify the type of the variables explicitly, if value is being initialised while declaring. Kotlin explicitly does it for you. Compiler knows the type of variable by the initialiser expression. Note that “Rahul Kumar” is a String and 40 is an Integer value. Compiler specify the type of the variable according to the value assigned to it while declaring it. Thus, data type of name is String and that of marks is Integer. This is called type inference in programming.
– Exercise
var averageMarks = 80.5;
2. Guess the data type of passPercent variable.
var passPercent = 70.5f;
Other ways to declare kotlin variables
It’s not always necessary to initialise the kotlin variable while declaring it. You can also assign the value after it is declared. In this situation, you must specify the data type of the variable explicitly. You can declare and specify the data type of the variable in one statement and assign the value in another statement later in the program. For example,
var name: String // Declare and specify the data type String. name = "Rahul Kumar" // Assign the value "Rahul Kumar" to the variable. var marks: Int // Declare and specify the data type Int. marks = 40 // Assign value 40 to the Integer variable.
– Exercise
1. Is this proper kotlin variable declaration and assignment?
var name name = "Rahul Kumar"
2. Is this proper kotlin variable declaration and assignment?
var name: String name = 40;
3. Is below kotlin variable declaration OK?
var name, fullName, firstName: String
4. Is below variable declaration and assignment OK?
var name: String name = "Rajeev Kumar"
Difference between var and val in kotlin
There are 2 types of variables in kotlin.
a. Mutable variable: It is read-write variable. A variable that can be changed.
b. Immutable variable: It is read-only variable. A variable that can not be changed once it is created.
val keyword is used to declare immutable variable while var keyword is used to declare mutable variable. Means, a variable declared using val keyword can not be re-assigned. while, a variable declared using var keyword can be re-assigned. For example,
Mutable kotlin variable
var x=10 // ok x = 20 // ok
Immutable kotlin variable
val y = 20 //ok y=30 //error
– Exercise
1. What is output of below program?
fun main (args : Array) { var name: String name = "Rajeev Kumar" println(name) name = "Rahul Kumar" println(name) }
2. What is output of below program?
fun main (args : Array) { val name: String name = "Rajeev Kumar" println(name) name = "Rahul Kumar" println(name) }
How to name a variable in Kotlin?
Well, let’s take an example to answer this question
var marks = 20;
Here, var is a keyword to declare variable and it’s given a name marks whose value is 20. There is a term called Identifiers. Identifiers are the name of the variables, classes or methods etc. Here, marks is variable that holds value 20.
There are some rules or conventions you should follow while naming any variables –
a. It starts with a letter or underscore followed by zero, letter or digits.
For example,
var name // ok var name20 // ok var 20name // error var _name //ok
b. Whitespaces are not allowed.
For example,
var full Name; // wrong var fullName; // right
c. Identifiers are case sensitive.
i.e marks and Marks are two different variables.
d. It can not contain special symbols such as @, #, % etc.
For example,
var name# // error var name@ // error
e. The name chosen should be self explanatory.
If a variable is created that holds marks of a student in the class, then, it’s name should be marks. For example,
var marks = 30;
marks is a variable that holds value 30.
Let’s take another example,
Suppose you need to create a variable that holds marks of students in the class. Then, The variable should be an array that holds integer value. It’s name should be marksArray.
var marksArray: IntArray = intArrayOf(10, 20, 30, 40, 50)
Similarly, you can choose any name of the variable depending upon the requirements etc.
Suppose name of the variable contains multiple words, then, you should use lowercase letters for first word and Upper case letter for first letter in the each subsequent word. Writing name of the variables in this way increase readability of the code. For Example,
var firstName = "Rahul"; var lastName = "Kumar"; var fullName = "Rahul Kumar";
Some valid Identifiers
Here are some valid identifiers –
score, marks, name, fullName, firstName, lastName, highestScore, number1, calculateTraffic, computeValue
Some Invalid Identifiers
Here are some invalid identifiers –
class, var, val, Int, as, break, false, true, this, throw, when, return, try, typealias, null, 2marks, full Name, last Name, first Name, total Num etc.
Conclusion
Here, we learnt about kotlin variables. We learnt how to declare and define kotlin variables. Whenever you are going to create a variable, always try to name the variable according to the task being done by the variable. For example, If you want to create a kotlin variable that holds population of a country, you can name it as population. Always try to follow the recommended rules for naming a variable. This way read-ability of your code will increase.