Search code examples
scalascalaz

Benefit of defining a trait whose purpose is only to mix into an object?


In scalaZ (file Id.scala), the context is like the following

/** Mixed into object `Id` in the package object [[scalaz]]. */
trait IdInstances {

....
}

object Id extends IdInstances

So why not directly use the following without first defining IdInstances? What's the benefit of doing like in Id.scala?

object Id {
   ...//with the same context from within IdInstances
}

Solution

  • The trait defines the contract and then then object provides the concrete implementation (just by mixing in the trait). This way, things that need the methods on the trait can refer to it by the trait as opposed to the object, allowing for things like dependency injection and mocking for testing and such. If all you had was the object then those types of things are very difficult to do