Subscribe Now

* You will receive the latest news and updates on your favorite celebrities!

Trending News

Blog Post

Difference between var, val and const in Kotlin
Kotlin

Difference between var, val and const in Kotlin

A variable declaration is always an important part of any programming language. In Kotlin there are mainly three keywords used to declare a variable that is var, val and const.

 

Use of “var” in Kotlin

We can change the value of a variable which is declared using the ‘var’ keyword. So var is used to declare a mutable variable.

Example:

var str:String = "Hello"
//we can change value of “str” if it is defined using ‘var’ keyword.
str = "World" //This will not generate any error

Some more examples for variable declarations:

val a: Int = 1 // readonly value
var x = 5 // `Int` type is inferred
var isSelected = false // Boolean variable
var isSelected:Boolean = false

Use of “val” in Kotlin

‘val’ is the same as the final modifier in java. As you probably know that we can not re-assign value to a final variable again. so ‘val’ is used to declare immutable variables.

Example:

val str:String = "Hello"

// now if you try to reassign value to "str"
str = "World" // this will show you error "val cannot be reassigned"

Use of “const” in Kotlin

The ‘const’ keyword is used to declare those variables which are immutable in nature i.e. these properties are read-only properties.

You can declare the ‘const’ variable only if a variable is
1. top-level or member of the object or member of a companion object.
2. must be initialized with a String type or primitive type.
3. no custom getter.

So, you can’t assign a const variable to a function or to some class because in this case the variable will be initialized at the runtime and not at compile-time.

What is the difference between ‘const’ and ‘val’?

‘const’ is also known as a Compile-time constant. So you cannot assign value to the ‘const’ type variable on runtime. On the other hand, ‘val’ type variable can be assigned on runtime. That’s why we can say ‘val’ type constants are runtime constants.

Example:

companion object {
        const val FILE_EXTENSION = ".png"
        const val FILE_NAME = getFileName() //This will give error "Const 'val'
        //initializer should be a constant value" 

        val savedFileName = getFileName() //This will not give any error

        fun getFileName(): String {
            return "IMG_" + System.currentTimeMillis() + FILE_EXTENSION
        }
    }

In above example, we tried to assign value to the const variable at runtime. But that will give us error “Const ‘val’ initializer should be a constant value.” and other hand we tried to assign value to val variable which will run successfully. 

That is all difference between var, val and const.

 

Do you want to learn Kotlin? Check my youtube video free of charge.
Subscribe to Android4Dev Youtube Channel:

Related posts

Leave a Reply

Required fields are marked *