how much should I care about putting constant strings into companion objects?
Copy code
// A
fun example() = "banana"
// B
companion object {
const val X = "banana"
}
fun example() = X
I guess benefit is storing variable to heap. But on the other hand, I think that adding single-use constants impacts code readability. Any thoughts?
f
Fleshgrinder
03/31/2022, 8:02 AM
Using single-use constants all over the place increases mental load because you need to navigate all around, and cannot know if they are single-use or not without searching.
The danger is when a single-use needs another use, since it could be forgotten to update the previously single place where the value was used.
e
ephemient
03/31/2022, 8:02 AM
the only concern should be readability/maintainability. there is no runtime impact, either way it will compile to a load from the constant pool
ephemient
03/31/2022, 8:06 AM
(with an exception for strings that, when MUTF-8 encoded, are longer than 64kB-1 because they won't fit into a single constant entry anymore so the Kotlin compiler inserts a runtime concatenation, but you won't be able to
const
it)
p
Peter Mandeljc
03/31/2022, 8:18 AM
Does string end up in same constant pool in both cases (heap / stack)?
s
Strum355
03/31/2022, 9:29 AM
The constant pool is an independent construct from stack and heap