Variables and constants. Keywords var, val, const
Contents
- 1. The purpose of using variables and constants. The need to use variables and constants in the program. Variable types
- 2. The syntax for declaring a mutable variable. The keyword var
- 3. An example of declaring variables of various types using the var keyword
- 4. Read-only variables (immutable variables). Using the val keyword in a variable declaration. Syntax
- 5. An example of declaring and using read-only variables
- 6. Constant declaration syntax. The keyword const
- 7. Examples of declaring constants
- 8. What is static typing?
- 9. What is auto-type detection?
- Related topics
Search other resources:
1. The purpose of using variables and constants. The need to use variables and constants in the program. Variable types
In the Kotlin language, the fundamental unit of any program is variables and constants. They are used to store data (values) in a program.
The data is described by the corresponding types. Therefore, variables and constants are of a certain type. You can read more about data types here.
Each variable or constant stores some value of a certain type. The data type determines the size of the memory cell that will be allocated for a declared variable or constant.
Depending on the algorithm for solving the problem, the program can use any number of variables or constants.
Each variable or constant has a name that is specified when it is declared.
The variable name is chosen so that it matches the purpose of this variable in the program. For example, it is advisable to denote the number of elements by the names length or count, and the volume of an object by the name volume.
Choosing the right names in the program has the following interrelated benefits:
- increases the readability of the program;
- facilitates the maintenance of the program by other programmers;
- the risk of making mistakes that may arise as a result of confusion in names is reduced.
Variables of two types can be declared in the program:
- mutable variables (references) that are declared using the var keyword. The value of such a variable in a program can be changed many times;
- immutable variables (references) or read-only variables. In this case, the keyword val is used. Such a variable cannot be assigned a value after initialization (a variable is assigned a value only once). These variables correspond to the final variables of the Java language.
⇑
2. The syntax for declaring a mutable variable. The keyword var
Any variable in the program on Kotlin language can be declared in one of two ways:
- without initialization;
- with initialization.
The syntax (general form) of declaring a variable without initialization is as follows:
var VariableName: Type
here
- VariableName – the name of variable;
- Type – the type of varibable (Int, Double etc.). You can read more about the basic data types here.
After such a declaration, the variable can be assigned values of the Type type or another type compatible with the Type type.
The syntax for declaring a variable with initialization allows you to immediately assign the desired value to a variable
var VariableName: Type = Value
here
- VariableName – the name of the variable that will store data of the Type;
- Value – some value. This value can be a literal, the name of another variable or constant, the result of a return from a function.
If VariableName is assigned a value of a type that is not or is incompatible with Type, the compiler will generate a type incompatibility error.
⇑
3. An example of declaring variables of various types using the var keyword
fun main(args:Array<String>) { // The var keyword // 1. Declaring variables without initialization // 1.1. Variable x of Short type var x : Short // later the variable x can be assigned some value of type Short x = 100 // 1.2. Variable y of type String var y : String y = "bestprog.net" // 1.3. Variable z of type Float var z : Float z = 1234.56f println("x = " + x) println("y = " + y) println("z = " + z) // 2. Variable declaration with initialization // Declare variable a of Double type // and assign it 12.88 var a:Double = 12.88 // Declare variable b of Int type // and assign the whole part of the variable a to it var b:Int = a.toInt() // b = 12 // Declare a variable c of type Char and assign a value to it var c:Char = '+'; // Declare a variable d of type String and assign a string to it var d:String = "Hello world!"; println("a = " + a) println("b = " + b) println("c = " + c) println("d = " + d) }
Program execution result
x = 100 y = bestprog.net z = 1234.56 a = 12.88 b = 12 c = + d = Hello world!
If in the above code try to assign a numeric value to the variable y
... // 1.2. Variable y of type String var y : String // Attempting to assign a numeric value to the variable y y = 120 // compilation error ...
the compiler will generate an error
Error:(17, 9) Kotlin: The integer literal does not conform to the expected type String
This is logical, since the variable y when declared is of type String and it is impossible to assign a numeric value to it.
⇑
4. Read-only variables (immutable variables). Using the val keyword in a variable declaration. Syntax
The Kotlin language allows you to use read-only variables. These variables have constant values throughout the entire execution time of the program. These variables are not constants. They can only receive a value once.
For example, if a program works with a certain file, then it is allowed to specify the file name once at the beginning of the program, in order to then use this file many times.
If a read-only variable is initialized, trying to change that value again will cause a compilation error.
As in the case with var-variables (see item 2) in the Kotlin language it is allowed to declare read-only variables in one of two ways:
- without initial initialization;
- with initial initialization.
The general form (syntax) of declaring a read-only variable without initial initialization is as follows
val VarName : Type
here
- VarName – the name of the variable being declared;
- Type – the type of the variable being declared.
After such a declaration, a variable can be assigned a new value only once.
VarName = Value
where Value is some value, literal, variable, constant, or the result of a return from a function.
Accordingly, the syntax for declaring a read-only variable with initial initialization is as follows
val VarName : Type = Value
⇑
5. An example of declaring and using read-only variables
fun main(args:Array<String>) { // The keyword val // 1. Declaration without initialization // 1.1. For Long type val a : Long a = 1_000_000_000_000_000_000 //a = 300 // here is an error, it is forbidden to change the variable a again // 1.2. For Char type val c : Char c = '&' println("a = " + a) println("c = " + c) // 2.1. Declaration with initialization // 2.2. For Byte type val d : Byte = 15 // 2.2. For String type val fileName = "myfile.txt" println("d = " + d) println("fileName = " + fileName) }
Program execution result
a = 1000000000000000000 c = & d = 15 fileName = myfile.txt
If in the above code you try to change the value of the variable a again
a = 300 // here is an error, it is forbidden to change the variable a again
then the compiler will generate an error
Error:(11, 5) Kotlin: Val cannot be reassigned
⇑
6. Constant declaration syntax. The keyword const
In the Kotlin language, it is allowed to declare constants – names that receive immutable values during program execution. These are values that never change in the program. They are also called compile-time constants, since the values of constants are assigned at compile time (at the moment when the program is compiled).
Constants can only receive values of basic types: Int, Double, Float, Long, Short, Byte, Char, String, Boolean.
The const modifier is used to declare a constant.
To declare a constant in a program, it is necessary that this constant be in the global scope. It will not be possible to declare a constant in the local scope (in the body of the function).
On an attempt to declare a constant in the body of a function (within curly braces {}), the compiler will generate an error.
The syntax for declaring a constant has two flavors:
- with an explicit indication of the type of the constant;
- without explicitly specifying the type of the constant. In this case, the type of the constant is determined by the type of the resulting value (literal).
The syntax for declaring a constant with an explicit type is as follows
const val ConstantName : Type = Value
here
- ConstantName – the name of the constant. When using this name in the program, the Value will be substituted;
- Value – the value that the constant receives.
The syntax for declaring a constant without explicitly specifying the type is
const val ConstantName = Value
⇑
7. Examples of declaring constants
Constants are declared in the global scope, that is, outside the main() function or any other function.
// Constant declaration - global scope // 1. Without explicit type indication const val Pi = 3.1415; // the constant of Double type const val Language = "Kotlin" // the constant of String type // With type indication const val Max : Int = 200 // the constant of Int type // fun MyFun() { // It is forbidden to declare constants here // ... } fun main(args:Array<String>) { // It is forbidden to declare a constant in the local scope // Using constants Pi, Language, Max in the main() function println("Pi = " + Pi) println("Language = " + Language) println("Max = " + Max) }
Program execution result
Pi = 3.1415 Language = Kotlin Max = 200
If in the above code you try to declare a constant in the body of the main() function
fun main(args:Array<String>) { // It is forbidden to declare a constant in the local scope const val Radius = 1.5 // compilation error // ... }
then the compiler will generate an error
Error:(22, 5) Kotlin: Modifier 'const' is not applicable to 'local variable'
⇑
8. What is static typing?
The Kotlin language implements static typing. This is a test by compiler of source code written by the programmer for correctness and type compatibility.
In the context of the above, a distinction is made between static type compatibility checking. This check allows you to see errors even before the code is compiled.
⇑
9. What is auto-type detection?
Automatic type detection is the determination of the type of a variable or constant based on the value it receives when it is declared.
Each value that is assigned to a variable or constant has a specific type. If you do not specify their type in the declaration of a variable or constant, then this variable or constant will take the type of the value that it receives.
Example. The example declares variables and constants that get different types based on the values they get.
// Float constant declaration const val constFloat = 1.777F // 1.777F - value of Float type // Declaration a constant of Long type const val Max = 10000000000L ... // Declaring a variable of type Char var c1 = 'Z' val c2 = 'X' // Declaring a variable of type Double var a = 2.5 var b = 3.8 val c = 2.7
⇑
Related topics
⇑