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?
const
s are compile time constants. Meaning that their value has to be assigned during compile time, unlike val
s, where it can be done at runtime.
This means, that const
s 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
const val foo = "Hello world"
and val bar = "Hello world"
? Are they the same? — Jun 02, 2016 at 15:32 const
values will just be completely inlined during compilation. — Jun 02, 2016 at 15:35 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 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