Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for global constants in Scala Application

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"?

like image 558
mkUltra Avatar asked Sep 02 '17 10:09

mkUltra


People also ask

How do you keep constants in Scala?

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.


1 Answers

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.

like image 59
pedromss Avatar answered Oct 11 '22 13:10

pedromss