简体   繁体   中英

Scala style: More than one class in a file?

Unlike Java, Scala supports putting multiple classes in one file. Since Scala's classes are often quite short (think case classes), this often seems to make sense.

What is considered the proper style and idiom to do this, on production code? Under what circumstances should short or associated classes be put in the same file? How should that file be named?

This is all covered in Scala style guide

Summary :

  • As a rule of thumb, you should have one logical compilation unit (ie trait, class, object) per file.
  • Exception made of companion objects where you can have them as well as their original trait/class in the same file
  • Another exception is sealed trait with its subclasses
  • Last exception is if it makes way more sense maintenance wise (ie your logical compilation units forms a inseparable, cohesive group)
  • Multi-unit file should have a lowercase first letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM