title: Scala: difference between usage of singleton vs trait/class
body: <p>I wanted to know the implications of using mixins vs singletons. As most of us agree, singletons are evil because they maintain state and it's hard to keep track of that state. Traits are superior because they can be mixed-in, mocked easily etc.. But I wanted to know the actual implications of what's happening under the hood: How using mixins does not cause problems ?</p>
  
  <p>The below code samples are just for the sake of demonstration of my problem.</p>
  
  <p>Approach #1: Using singletons all over:</p>
  
  <pre><code>object Server {
    def fetchData(input: Input): String = ...
  }
  object Servers { 
    val inMemoryServers: Seq[Server] = ...
    def randInMemServer = Random.shuffle(Servers.inMemoryServers).head
  }
  object AppClient {
    def execute(input: Input) = {
      Servers.randInMemServer.fetchData(input)
    }
  }
  </code></pre>
  
  <p>Approach #2: Using mixins</p>
  
  <pre><code>trait Server2 {
    def fetchData(input: Input): String = ...
  }
  trait Servers2 extends Server2 { 
    val inMemoryServers: Seq[Server] = ...
    val httpServers: Seq[Server] = ...
  }
  case class DataA(input: Input) extends Servers2 {
    def getA = inMemoryServers
  }
  case class DataB(input: Input) extends Servers2 {
    def getB = ...
  }
  object DataC extends Servers2 {
    def getC(input: Input) = ...
  }
  object AppClient2 {
    def execute(input: Input) = {
      val a = DataA(input).getA // line 1
      val b = DataB(input).getB // line 2
      val c = DataC.getC(input) // line 3
    }
  }
  </code></pre>
  
  <p>How many instances of Server2 and Servers2 are created in AppClient after line 3 ? </p>
  
  <p>Say if Server2 had a variable to create a threadpool (with say 5 threads, see below), how many there are created after (line 3) ? </p>
  
  <pre><code>trait Server2 {
    val pool: Threadpool = ... // create a pool of 5 threads
    def fetchData(input: Input): String = ...
  }
  </code></pre>
  
  <p>What are the implications if the Server2 declared the members as <code>def</code>s instead of <code>val</code>s as shown below ? Are new thread pools created in each of the lines 1, 2 and 3 ?</p>
  
  <pre><code>trait Servers3 extends Server2 { 
    def threadPool: Threadpool = ...
    def inMemoryServers: Seq[Server] = ...
  }   
  </code></pre>