【问题标题】:How to assign a value to a constant depending on another constant value in Kotlin?How to assign a value to a constant depending on another constant value in Kotlin?
【发布时间】:2022-12-02 04:38:40
【问题描述】:

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?

【问题讨论】:

    标签: kotlin jvm constants


    【解决方案1】:

    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.

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2022-12-01
      • 2022-12-01
      • 2022-12-02
      • 2022-12-01
      • 2022-12-27
      • 1970-01-01
      • 2022-12-26
      相关资源
      最近更新 更多