OutOfMemoryError occurs no matter what you use Stream. As Rex Kerr mentioned, Stream - unlike Iterator - stores everything in memory. The difference with List is that Stream elements are calculated lazily, but once you reach 10,000,000, there will be 10,000,000 elements, like List.
Try with new Array[Int](10000000) , you will have the same problem.
To calculate the fibonacci number as stated above, you can use a different approach. You can take into account the fact that you only need to have two numbers, and not all the fibonacci numbers found so far.
For instance:
scala> def fib(i:Long,j:Long): Iterator[Long] = Iterator(i) ++ fib(j, i + j) fib: (i: Long,j: Long)Iterator[Long]
And to get, for example, the index of the first Fibonacci number in excess of 1,000,000:
scala> fib(1, 1).indexWhere(_ > 1000000) res12: Int = 30
Edit: I added the following lines to handle StackOverflow
If you really want to work with the 1 millionth fibonacci number, the definition of the iterator above will not work for a StackOverflowError either. The following is the best that I have in mind at the moment:
class FibIterator extends Iterator[BigDecimal] { var i: BigDecimal = 1 var j: BigDecimal = 1 def next = {val temp = ii = i + j j = temp j } def hasNext = true } scala> new FibIterator().take(1000000).foldLeft(0:BigDecimal)(_ + _) res49: BigDecimal = 82742358764415552005488531917024390424162251704439978804028473661823057748584031 0652444660067860068576582339667553466723534958196114093963106431270812950808725232290398073106383520 9370070837993419439389400053162345760603732435980206131237515815087375786729469542122086546698588361 1918333940290120089979292470743729680266332315132001038214604422938050077278662240891771323175496710 6543809955073045938575199742538064756142664237279428808177636434609546136862690895665103636058513818 5599492335097606599062280930533577747023889877591518250849190138449610994983754112730003192861138966 1418736269315695488126272680440194742866966916767696600932919528743675517065891097024715258730309025 7920682881137637647091134870921415447854373518256370737719553266719856028732647721347048627996967...