通常我创建一个“
Scala对象”来保存我所有的全局常量.
我被告知最好使用“包对象”来保持常量.
我之前从未使用过“包对象”,所以我的问题是:
我被告知最好使用“包对象”来保持常量.
我之前从未使用过“包对象”,所以我的问题是:
在Scala中保存常量的最佳实践是什么?为什么?
为什么我需要“包对象”?
解决方法
你不需要一个包对象.
但是,它允许您在包级别创建代码而不声明另一个类或对象.
这很方便.
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. }
为常量指定的唯一约定是关于casing.常量应该是PascalCased
请记住,在包对象中声明常量可能会使它们在您不希望它们可用的位置可用.
我给你留下naming convention包装对象:
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.