Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
Geo Avatar asked Apr 23 '11 11:04

Geo


3 Answers

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
like image 123
Stefan Endrullis Avatar answered Oct 23 '22 14:10

Stefan Endrullis


Package objects or just plain objects.

See, for instance, Scala.Predef and scala.math.

like image 29
Daniel C. Sobral Avatar answered Oct 23 '22 15:10

Daniel C. Sobral


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.

like image 37
pedrofurla Avatar answered Oct 23 '22 15:10

pedrofurla