Search code examples
constantskotlin

What is the difference between "const" and "val"?


I have recently read about the const keyword, and I'm so confused! I can't find any difference between const and the val keyword, I mean we can use both of them to make an immutable variable, is there anything else that I'm missing?


Solution

  • consts are compile time constants. Meaning that their value has to be assigned during compile time, unlike vals, where it can be done at runtime.

    This means that only a String or primitive can be assigned to a const, not the result of a function or class constructor invocation.

    For example:

    const val foo = complexFunctionCall()   //Not okay
    val fooVal = complexFunctionCall()      //Okay
    
    const val bar = "Hello world"           //Also okay