Error while implementing take for a Stream <p>I was trying to solve Exercise 2 from <a href="http://www.manning.com/bjarnason/" rel="nofollow">Functional Programming in Scala</a>. The question is as follows:</p> <blockquote> <p>EXERCISE 2: Write a function take for returning the first n elements of a Stream. ￼def take(n: Int): Stream[A]</p> </blockquote> <p>My solution is as follows:</p> <pre><code> import Stream._ trait Stream[+A]{ def uncons:Option[(A,Stream[A])] def isEmpty:Boolean = uncons.isEmpty def toList:List[A] = { val listBuffer = new collection.mutable.ListBuffer[A] @annotation.tailrec def go(str:Stream[A]):List[A] = str uncons match { case Some((a,tail)) =&gt; listBuffer += a;go(tail) case _ =&gt; listBuffer.toList } go(this) } def take(n:Int):Stream[A] = uncons match { case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) case _ =&gt; Stream() } } object Stream{ def empty[A]:Stream[A] = new Stream[A]{def uncons = None} def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ lazy val uncons = Some((hd,tl)) } def apply[A](as: A*):Stream[A] = { if(as.isEmpty) empty else cons(as.head,apply(as.tail: _ *)) } } </code></pre> <p>I store this as Stream2.scala and then from the REPL I execute the following:</p> <pre><code>:load Stream2.scala </code></pre> <p>When the REPL tries to load my script, it barfs with the following errors:</p> <p>scala> :load Stream2.scala</p> <pre><code>Loading Stream2.scala... import Stream._ &lt;console&gt;:24: error: type mismatch; found : Stream[A] required: scala.collection.immutable.Stream[?] case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) ^ &lt;console&gt;:25: error: type mismatch; found : scala.collection.immutable.Stream[Nothing] required: Stream[A] case _ =&gt; Stream() ^ &lt;console&gt;:11: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def empty[A]:Stream[A] = new Stream[A]{def uncons = None} ^ &lt;console&gt;:12: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ </code></pre> <p>Can somebody point out what might be going wrong here?</p>