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?
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.
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
constvalues will just be completely inlined during compilation. — Jun 02, 2016 at 15:35
const valinstead of just
const? It seems to me the
valkeyword is totally superfluous in this context, since
const varwould be absurd on its face. — Jun 08, 2017 at 15:51
constis a modifier on
valrather than a keyword. Modifiers > keywords. More examples of this same design are,
inline fun, etc. — Apr 02, 2018 at 19:36