Question

I have some values and methods to define in a scala object.

I do not know in which order I should define them. Is there a "good way" to do it? Such as private methods first then public methods? Only alphabetically ordered?

Was it helpful?

Solution

There is no strong convention. You can consider applying the old Java Coding Conventions to Scala, but they are fairly vague. They recommend the following order of declarations with a class or interface:

  • Class ( static) variables. First the public class variables, then the protected, then package level (no access modifier), and then the private.

  • Instance variables. First public, then protected, then package level (no access modifier), and then private.

  • Constructors.

  • Methods These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

This doesn't apply directly to Scala as it uses companion objects instead of static variables, and fields are indistinguishable from methods. However, you can still try to put object state first and any behavior second. The JCC recommendation to group by functionality rather than by access or name is a good one: things that change together should be close together.

Licensed under: CC-BY-SA with attribution
scroll top