Usually I create a "Scala Object" that keeps all my global constants. I have been told that it is better to use "package object" in order to keep constants. I have never used "package object" previously so my questions are:
What are the best practices to hold constants in Scala and why?
Why do I need "package object"?
Constants must always follow the PascalCase naming rule, according to the default style used in Scala community. Do not use CAPITAL_SNAKE_CASE or camelCase for constant names. Constants must always be defined in objects. If a constant is only used in one class, then it should be defined in its companion object.
You dont need a package object.
However it allows you to make code available at the package level without declaring another class or object.
It's a convenience.
package foo.bar
package object dem {
// things here will be available in `foo.bar` package and all subpackages
// without the need of an import statement.
}
The only convention specified for constants are regarding casing. Constants should be PascalCased
Keep in mind that declaring constants in the package object might make them available in places where you don't want them to be available.
I leave you the naming convention for package objects:
The standard naming convention is to place the definition above in a file named package.scala that's located in the directory corresponding to package pp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With