Question

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
}
Was it helpful?

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

OTHER TIPS

There is a common pattern for such trait usage.

trait FromNumber {
  implicit def int2string(i : Int) : String = s"int value of $i"
  implicit def double2string(d : Double) : String = s"double value of $d"
}
object FromNumber extends FromNumber

trait ToNumber {
   implicit def string2int(s : String) : Int = s.toInt
   implicit def string2double(s : String) : Double = s.toDouble
}
object ToNumber extends ToNumber

trait Implicits extends FromNumber with ToNumber
object Implicits extends Implicits

So values presented in the trait may be either used in an extended class or accessed directly from the companion object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top