Which is preferred?
# announcements
s
Which is preferred?
r
Depends on the use case but without further context I'd either do 2 or
Copy code
class ClassName {
    companion object {
        private const val CONST_VALUE = "value"
    }
}
j
Short answer: 2 (or in a
ClassName
companion object, but I prefer top level)
r
@joelpedraza Great minds and all that 🙂
h
I put them at the top level as well
s
why companion? I prefer to not use companion If at all possible.
j
As a rule I go with top level for private const, companion for public (to avoid polluting the global namespace)
👍 1
r
If the value is only used with the class, it makes the intent more clear.
👍 1
s
The drawback of top level is that your Kotlin class file becomes Kotlin file. You loose the association between file and class in the IDE
I think creating companion for storing constants is overkill
j
Tangential to the rest of the conversation: Either way a new class is created
s
not with option 1 if I'm not wrong
r
No, not for option 1, but that won't actually be a compile time constant.
j
True but then every instance of your class has a field to hold what should be a shared static or const
If it’s a concern for you any tree shaking optimization will remove it. IIRC consts are inlined for kotlin usages, but java usages access the field
s
@joelpedraza You mean the field in option 1?
j
No, top level or companion