Signup/Sign In
LAST UPDATED: AUGUST 10, 2020

Kotlin Variables and Constants

In this tutorial, we will discuss variables in Kotlin. A variable is basically a memory location that is used to hold some data. Each variable is assigned a unique name which is known as its identifier.

In Kotlin, we can declare a variable using two keywords:

  1. val

  2. var

Kotlin val keyword

The val keyword is used to declare a "read-only" variable i.e. an immutable variable. In simple terms, it is not possible to reassign a value to a variable marked with val keyword.

For example:

val name = "Hello"
name = "World!!"    //Error: Val cannot be reassigned

It is advised to use val when during the lifetime of a variable, it needs to be assigned only once like creating an object of a class. It also makes sure that the developer does not accidentally reassign value to a variable that should not change.

Kotlin var keyword

The var keyword is used to declare mutable variables i.e. variables whose value can be changed and reassigned to it.

var name = "Hello"
println(name)     
name = "World!!"
println(name)


Hello
World!!

Constants in Kotlin

Kotlin constants are used to define a variable that has a constant value. The const keyword is used to define a constant variable. The const keyword can only be used with the val keyword and not with the var keyword.

const val empName = "employee_1"
println(empName) 


employee_1

If we try to declare a constant with var keyword, we will get error: "Modifier 'const' is not applicable to 'vars' "

Difference between const and val

Both the val and const keywords seem to be doing the same work i.e. declare constant variables. But there is a slight difference between them. The const keyword is used to declare compile-time constants while the val keyword can declare runtime constants. Let us understand it with an example:

Suppose we declared a variable empName and we want to assign it a value, which will be returned by a function sayHello(). If we use the val keyword, we will not get any error:

val empName = sayHello()        // No error

fun sayHello():String{
    return "Hello"
}

But, if we declare this variable with const keyword, we will get an error because the value will be assigned to empName at runtime:

const val empName = sayHello()        // we will get error

fun sayHello():String{
    return "Hello"
}

So, the const keyword is used to declare variables whose values are known at compile-time only.

Summary

In this tutorial, we discussed types of variables in Kotlin. We also saw the use of const keyword and difference between the val and the const keyword. In the next tutorial, we will discuss data types in Kotlin.



About the author:
I'm a writer at studytonight.com.