Open In App

Kotlin Variables

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. The declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.

Example 1:

Kotlin
fun main()
{
    var rollno : Int = 55
	var name = "Ram"
	println(rollno)
	println(name)
}

Output:

55
Ram


Example 2:

Kotlin
fun main()
{
	val a: Int = 1  // Explicit type declaration
	val b = 1       // Type is inferred by the compiler
    println(a)
    println(b)
}

Output:

1
1

Above we have the local variable rollno whose value is 55 and its type is Integer because the literal type is Int, and another variable is name whose type is String.

In Kotlin, variables are declared using two types:

  1. Immutable using the val keyword
  2. Mutable using the var keyword


Immutable Variables

Immutable is also called read-only variables. Hence, we can not change the value of the variable declared using 'val' keyword.

val myName = "Gaurav"
myName = "Praveen" // compile time error

Output:

'val' cannot be reassigned

Note: An Immutable variable is not a constant because it can be initialized with the value of a variable. It means the value of an immutable variable doesn't need to be known at compile-time, and if it is declared inside a construct that is called repeatedly, it can take on a different value on each function call.

var myBirthDate = "02/12/1993"
val myNewBirthDate = myBirthDate
println(myNewBirthDate)

Output:

02/12/1993

Mutable Variables:

In a Mutable variable, we can change the value of the variable.

var myAge = 25
myAge = 26 // compiles successfully
println("My new Age is ${myAge}")

Output:

My new Age is 26

Note: To know more about val and var in kotlin refer this article: Difference between var and val in Kotlin.


Scope of a Variable

A variable exists only inside the block of code( {.............} ) where it has been declared. You can not access the variable outside the loop. The same variable can be declared inside the nested loop, so if a function contains an argument x and we declare a new variable x inside the same loop, then x inside the loop is different than the argument.

Naming Convention:

Every variable should be named using lowerCamelCase.

Example:

val myBirthDate = "02/12/1994"

Next Article
Article Tags :
Practice Tags :

Similar Reads