in my class I need to use a string for a key name....
# getting-started
c
in my class I need to use a string for a key name. I want to make sure I don't typo. so I want to pull it out into a constant. Option A:
Copy code
const val SOME_KEY_NAME = "MY_KEY_NAME"
cons... pollutes everywhere else having access to this? Option B:
Copy code
companion object {
    const val SOME_KEY_NAME = "MY_KEY_NAME"
}
cons... people seem to look down upon companion objects. is there a way to just share the key name privately in the class?
r
Just make it private. For option A:
Copy code
private const val SOME_KEY_NAME = "MY_KEY_NAME"
makes it private to the file. For option B:
Copy code
companion object {
    private const val SOME_KEY_NAME = "MY_KEY_NAME"
}
makes it private to the class.
people seem to look down upon companion objects
It's not that companion objects are bad and should be avoided. They're just a bit heavyweight sometimes for some of the simpler use cases, and so there's some active work on finding a simpler way to handle those use cases. Until then, companion objects are fine.
👍 1
Also note that making it private to the file won't necessarily save you an extra object/class over a companion, as a class gets created per file to hold top level declarations (on the JVM).
c
what would you choose in this case?
r
I don't really know what "this case" is, so I can't really say. The companion has a more restricted scope, which could be a plus or a minus. Ultimately I'd say just go with what makes the most sense to you.