Why is the `const` keyword necessary? I understand...
# language-proposals
e
Why is the
const
keyword necessary? I understand that
const val
is for compile-time constants and leads to different (presumably better) code than
val
, but why couldn't the compiler generate the better code if a [static]
val
is assigned a compile-time constant? In other words, why does the compiler generate different code for these two lines?
Copy code
const val PI = 3.1415
val PI = 3.1415
e
Java does that and it's a terrible idea
on the JVM, constant values are inlined everywhere they are used
this means changing constant values is an API change - e.g. if I release a library with
const val FOO = 1
, somebody else builds a library using
FOO
, and then I release a new version with
FOO = 2
, a consumer of both libraries will see mismatched values
(also within a multi-module Gradle build, this means that changing constant values forces Gradle to do additional work tracing every place where value got inlined, in order to recompile it, whereas changing a simple
val
does not change the API and dependents do not need to be recompiled)
there are good reasons to use
const
- they're necessary for use in annotations, for example, which also explains why they are inlined - but it is a significant decision to make regarding your API
👍 3
see also how the Android build system generates
Copy code
public class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
in order to create a static final but non-constant field
🙏 1
🙏 5
👍 2
s
that's odd. why don't they just use = Boolean.TRUE ?
they're trying to trick the compiler, but isn't it effectively the same value?
e
yes, forcing the compiler to unbox would also achieve the same goal, but they're also trying trick the IDE
s
what good does that do?
or, what does the IDE do that might be "wrong"?
e
avoiding "could be constant" diagnostics
s
ah
n
Just as a sidenote, this is somewhat related: https://youtrack.jetbrains.com/issue/KT-49303
Just as a sidenote, the Zig language has very advanced compile-time evaluation: https://ziglang.org/learn/overview/#compile-time-reflection-and-compile-time-code-execution