Const Keyword in Kotlin

Let’s learn about the const keyword in kotlin

Variables identified with the const keyword are immutable, as is val. The difference here is that const is applied to variables defined at compile-time. Declaration of a const attribute is just like using the Java static keyword.

Lets first see how ‘val’ works

1
2
val price: Int
       price = 5

I declared a variable with a val keyword and didnt initialize it. The compiler would allow me to do this, i can even initialize the val variable during run time but only once.

1
2
3
val price: Int
    price = 5
    price = 6

If i try to reinitialize the val variable compiler throws me error “Val can not be reassigned”

Lets see how to declare a const variable in kotlin

1
2
3
companion object {
        const val APP_NAME = "MyApplication"
    }

This is similar to static variable in java

1
final static String APP_NAME = "MyApplication"

Difference between val and const

The consts are compile time constants. This means that, unlike ‘val’s, their value has to be allocated during the compile time, where as for ‘val’s it can be done at runtime. That means consts can never be assigned to any function or class builder, but only to a string or primitive.I can do something like this for ‘val’

1
2
3
4
5
6
7
private fun getPrice(): Int {
        return 5
    }

    fun calculatePrice() {
        val modifiedPrice = getPrice()
    }

But i cannot do something like this below, compiler will throw error under const variable like “Const val initializer should be a constant value”

1
2
3
4
5
6
companion object {
        private fun getPrice(): Int {
            return 5
        }
        const val mod = getPrice()
    }