Reputation: 96937
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?
Upvotes: 13
Views: 3257
Reputation: 297265
Package objects or just plain objects.
See, for instance, Scala.Predef
and scala.math
.
Upvotes: 7
Reputation: 4208
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
Upvotes: 13
Reputation: 12783
Traits if you want them to be mixed in with the classes that are going to use it. Objects if you want to only have to import them.
Upvotes: 2