Programming
constants kotlin
Updated Fri, 05 Aug 2022 16:48:19 GMT

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 consts can never be assigned to a function or any class constructor, but only to a String or primitive.

For example:

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




Comments (5)

  • +3 – What about something like this: const val foo = "Hello world" and val bar = "Hello world"? Are they the same? — Jun 02, 2016 at 15:32  
  • +5 – @MathewHany, at least not in terms of bytecode, see: stackoverflow.com/questions/37482378/static-data-in-kotlin/… — Jun 02, 2016 at 15:34  
  • +5 – I think const values will just be completely inlined during compilation. — Jun 02, 2016 at 15:35  
  • +0 – This begs another question: Why does Kotlin require const val instead of just const? It seems to me the val keyword is totally superfluous in this context, since const var would be absurd on its face. — Jun 08, 2017 at 15:51  
  • +0 – @EricLloyd With const val, const is a modifier on val rather than a keyword. Modifiers > keywords. More examples of this same design are, annotation/enum/data class, private val, inline fun, etc. — Apr 02, 2018 at 19:36