Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

Scala: multiple objects and classes in a single file or each object/class its own file

I've recently started programming in Scala, coming from Python and Java I was wondering what the correct way or the accepted way is when defining objects/classes in Scala. Scala supports, just like python, to add several class or object definitions in a single file.

So purely from an accepted structure perspective, does every object need to be defined in its own file or are you allowed to choose this yourself?

question from:https://stackoverflow.com/questions/24365548/scala-multiple-objects-and-classes-in-a-single-file-or-each-object-class-its-ow

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a chapter in the official Scala Style Guide on this. It's pretty clear in itself, but I'll just leave some quotes here.

The core idea is:

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

There is, of course, an exception for companion objects:

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.

There is also the fact that sealed only works within 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.

Most of the time, case classes are just simple data containers and can be grouped together.

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.

Finally, there is a naming convention for exempted multi-unit Scala files:

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

So: put your Scala classes and objects in separate files, unless they fall into one of the three mentioned exceptions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...