This would be useful for me because I have a bunch of constants that are different when I test my program locally vs when I run it on the server that it's supposed to run on.
I assumed an if-else expression would work:
const val FOO = false
const val BAR = if (FOO) 1L else 2L
However, the compiler considers this an error because for some reason, this if-else expression is not considered to be constant even though it really should be in my opinion, just like arithmetic expressions with constant values can also be assigned to constants.
My first question is, why does this not work, and secondly and more importantly, is there a way to do this? Or am I just forced to make these fields not constant?
CodePudding user response:
According to the specification on constant properties, the only expressions that are allowed are:
Integer literals and string interpolation expressions without evaluated expressions, as well as built-in arithmetic/comparison operations and string concatenation operations on those are such expressions, as well as other constant properties, but it is implementation-defined which other expressions qualify for this;
This means only some very specific expressions and functions can be considered constants, and at the moment they are hard-coded in the compiler.
In any case, the if
expression is not considered possible to evaluate at compile time at the moment. However, there is an open ticket to potentially allow user-defined constant functions, which would enable that:
https://youtrack.jetbrains.com/issue/KT-14652
CodePudding user response:
This doesn't work since const
members of a class have to be initialized at the compile time. Indeed, const
is translated to final
in the java code generated from kotlin and the compile time initialization is needed for final
members.
The keyword val
is already giving you an immutable variable, as opposed to var
, and therefore technically a constant. Hence, you should be fine with just val
instead of const val
.