Search code examples
scalacode-organization

Preferred way of grouping utility functions in Scala?


What's the best way of grouping utility functions that don't belong in a class? In Ruby, I would have grouped them in a module. Should I use traits in Scala for the same effect, or objects?


Solution

  • Usually, I put utility functions that are semantically different into different traits and create an object for each trait, e.g.

    trait Foo {
      def bar = 1
    }
    object Foo extends Foo
    

    That way I'm most flexible. I can import the utility functions via an import statement or via with in the class declaration. Moreover I can easily group different utility traits together into a new object to simplify the import statements for the most commonly used utility functions, e.g.

    object AllMyUtilites extends Foo with Foo2