Declare Variables In Kotlin

Kotlin variables

In Kotlin, declaring a variable is slightly different from that of C, C++ and Java. Either var or val keyword is used for declaring variables.

var variable_name:data_type = value;
or
val variable_name:data_type = value;

for example

var x:Int = 10;

Here data_type and values are optional. If we did not declare the datatype for a variable, the compiler infers datatype for that variable.

Kotlin variable types

  • Mutable variable
  • Immutable variable
  • Global Variables / Top-level Variables

Types of variable declaration

  • Immediate assignment of Datatypes
  • Compiler Inferred Declaration
  • Deferred assignment Declaration

Mutable variables

The Mutable variables are declared with the var keyword. The value assigned to these variables can be changed later in the program like the regular variables in C, C++ and Java.

Mutable variables example program

// Mutable variables Kotlin example program
// Variable Kotlin Programs , Basic Kotlin Programs

fun main(args: Array<String>) {
    // Declared with datatype
    var x:Int = 100
    
    // Compiler Inferred Declaration : `Int` type is inferred
    var y = 200 
    
    println("X Value : $x")
    println("Y Value : $y")
}

Sample Output

X Value : 100
Y Value : 200

Immutable variables

The Immutable variables are declared with the val keyword. Once assigned, these values cannot be changed like the constant variables in C, C++ and Java.

Immutable variables example program

// Immutable variables Kotlin example program
// Variable Kotlin Programs , Basic Kotlin Programs

fun main(args: Array<String>) {
    
    // Declared with datatype
    val x: Int = 100
    
    // Compiler Inferred Declaration : `Int` type is inferred
    val y = 200
    
    // Deferred assignment Declaration : no initial value is provided
    val z: Int
    z = 300
    
    println("X Value : $x")
    println("Y Value : $y")
    println("Z Value : $z")
}

Sample Output

X Value : 100
Y Value : 200
Z Value : 300

Global Variables / Top-level Variables

In Kotlin, A global variable is a variable that is declared at the top of the program and outside all functions similar to C and C++. A local variable can only be used in the particular block where it is declared. A global variable can be used in all functions.

Global variables example program

// Global Variables / Top-level Variables Kotlin example program
// Variable Kotlin Programs , Basic Kotlin Programs

// Declared Global Variable `Int` type is inferred
var x = 100

fun fn() { 
    x = x + 100 
}

fun main(args: Array<String>) {
    println("X Value : $x")
    
    fn()
    
    println("X Value : $x")
}

Sample Output

X Value : 100
X Value : 200

More About Data Types and Its Usage