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?
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 [...], 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.
At the moment, the if
expression is not considered possible to evaluate at compile time. However, there is an open ticket to add support for this case. There is also a more general ticket to potentially allow user-defined constant functions, which would widen the possibilities even further.
is there a way to do this? Or am I just forced to make these fields not constant?
Not to my knowledge, so yes, just remove the const
and use a simple val
instead.