So, const values must be known at compile time. Hence we cannot use any kind of method to compute const values.
So, are non-const values (which we should take care to make immutable) allowed in a Companion Object? Or is an Companion Object explicitly for constants?
I think it's perfectly safe to use consts and non-consts in a companion object, as long as they're effectively immutable.
Any comments?
The interesting part is that, according to [1], Kotlin inlines the const values where they are actually used. So the definition of the constant has actually disappeared from the compiled byte code. Which is of course much faster, than having to access a constant field somewhere.
Fascinating stuff.
References
- [1] Baeldung - Kotlin const, var, and val Keywords
- https://www.baeldung.com/kotlin/const-var-and-val-keywords
No comments:
Post a Comment