Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala trait and class in the same file

Is it a good practice to put a trait and class implementing it in the same file in Scala? E.g. in B.scala you have :

trait A
class B extends A
like image 780
Shamannn Shamannn Avatar asked Jan 04 '23 13:01

Shamannn Shamannn


2 Answers

You can, but if they're not closely related you better don't.

The pragmatic reason is that adding many classes/traits to a file may make the compilation (especially the incremental compilation) slower.

Here's an extract from https://virtuslab.com/blog/zinc-sbt-friendly-code/#less-is-more

Less classes/traits/objects per source file means more time saved. Scalac can compile nothing less than a whole source. Even if Zinc knows that only a one-line object needs to be recompiled, it still has to compile the whole source (and all implicits macros and other nasty stuff inside).

The solution is as simple as possible: split your sources! If incremental compilation is not enough to convince you, you should be aware that it should also help with compilation time or even result in less conflicts during merges.

Notable exceptions are:

  • families of sealed trait: sealed allows to extend a trait only within the source file, so you in this case you have to keep all the classes extending that trait together.

  • classes and companion objects: an object named after a class is considered its companion object only if its defined in the same source file, so again you have to keep them together.

The official style guide seems to confirm this approach, even though it doesn't explicitly mentions compilation performances:

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.

like image 114
Gabriele Petronella Avatar answered Jan 12 '23 09:01

Gabriele Petronella


Yes, you can make a class extend a trait in the same scala file. Also, check out sealed trait and see if it is relevant to you.

like image 34
Selvaram G Avatar answered Jan 12 '23 09:01

Selvaram G