Code style: companion objects above or below the class declaration?

I’ve always written my class declarations first followed by the companion object, if any. I guess I picked it up from the tutorial:

case class Circle(radius: Double) {
  import Circle._
  def area: Double = calculateArea(radius)
}

object Circle {
  private def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)
}

More recently I’ve noticed more examples of the companion object being declared at the top of the file and the class declaration following below it. Of course they are equivalent and this is completely subjective but I’m curious to know if this is a growing trend or has there been a shift in tastes by the community. Actually, is there any practical advantage I’m aware of?

If you write your companion objects at the top, why do you think it is better? Do you do it all the time? When do you choose not to do it?

1 Like

I don’t think it matters much which appears first; it’s just a matter of personal preference. I have a related question though. Using your example of a circle, suppose you need a way to determine the distance between two circles (or whether they overlap). Should that capability be implemented as a function in the companion object, taking the two circles as arguments, or should it be a method of the class, taking the other circle as the argument? Or should it be both, with one referring to the other? If so, which one should refer to the other?

I do admit this is completely subjective. Most discussions about style are. I’m looking to see if my personal taste can be influenced one way or another. My current preference is because the all earliest examples I saw had the class before the object. What’s your personal preference? Can you articulate why you feel it is better that way than the other?

As for your not-really-related-but-also-subjective question: I would judge it based on which reads better at the calling site.

usually companion object use companion class (for apply), so i prefer to see and be familiar with class before object.

Yes, especially coming from Java it’s more natural for me to have the class first. But I’ve also heard this argument that you put your static members first in Java and that in Scala that would be equivalent to the companion object and it’s members. What do you think about that?

1 Like