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?
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
Package objects or just plain objects.
See, for instance, Scala.Predef
and scala.math
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With