title: DAO in Scala with type classes
body: <p>Let my application contains business classes <code>Order</code>, <code>Product</code>, <code>Customer</code>, etc. and I would like to store/retrieve them in/from the database.</p>
  
  <p>Usually, we use the <code>DAO</code> pattern for this purpose. That is, we define a <code>DAO</code> interface and implementation for every business class: <code>OrderDAO</code>, <code>ProductDAO</code>, etc. Now I would like to use the <em>type class</em> pattern:</p>
  
  <pre><code>trait DAO[T] {
    def create(t:T)
    ... // other CRUD operations
  }
  ...
  // DAO implementations for specific business objects
  implicit object OrderDAO extends DAO[Order] {
     def create(o:Order) {...}
     ... // other CRUD operations
  }
  ...
  // create a business object in the database
  def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}</code></pre>
  
  <p>Now my problem is that all <code>DAOs</code> use a <code>DataSource</code> instance (a factory of database connections) and so I cannot define <code>DAOs</code> as <code>objects</code>. I should create a singleton instance of the <code>DataSource</code> and pass it to all <code>DAOs</code> upon their initialisation.</p>
  
  <p>Let's say we have a function to create a <code>DataSource</code>: <pre><code>def dataSource():DataSource = {...}</code></pre>
  How would you implement the <code>DAOs</code> with <em>type classes</em> ?</p>