Scala:单个文件中的多个对象和类,或每个对象/类自己的文件

我最近在Scala中开始编程,来自Python和Java我想知道在Scala中定义对象/类时,正确的方法或接受的方式是什么。 Scala支持,就像python,在单个文件中添加多个类或对象定义。

纯粹是从接受的结构角度来看,每个对象都需要在自己的文件中定义,还是允许你自己选择?

最佳答案
官方Scala Style Guide有一章。它本身很清楚,但我会在这里留下一些引语。

核心思想是:

As a rule, files should contain a single logical compilation unit. By “logical” I mean a class, trait or object.

当然,伴随对象有一个例外:

One exception to this guideline is for classes or traits which have companion objects. Companion objects should be grouped with their corresponding class or trait in the same file.

还有一个事实是,密封只能在同一个文件中工作。

Despite what was said above, there are some important situations which warrant the inclusion of multiple compilation units within a single file. One common example is that of a sealed trait and several sub-classes. Because of the nature of sealed superclasses (and traits), all subtypes must be included in the same file.

大多数情况下,病例类只是简单的数据容器,可以组合在一起。

Another case is when multiple classes logically form a single, cohesive group, sharing concepts to the point where maintenance is greatly served by containing them within a single file.

最后,有一个豁免的多单元Scala文件的命名约定:

All multi-unit files should be given camelCase names with a lower-case first letter.

所以:将Scala类和对象放在单独的文件中,除非它们属于上述三种异常之一。

转载注明原文:Scala:单个文件中的多个对象和类,或每个对象/类自己的文件 - 代码日志