Question: How can I initialize a val that is to be used in another scope? In the example below, I am forced to make `myOptimizedList` as a var, since it is initialized in the `if (iteration == 5){}` scope and used in the `if (iteration > 5){}` scope. 

```
val myList:A = List(...)
var myOptimizedList:A = null

for (iteration <- 1 to 100) {
    if (iteration < 5) {
        process(myList)
    } else if (iteration == 5)
        myOptimizedList = optimize(myList)
    } 
    if (iteration > 5) {
        process(myOptimizedList)
    }
}

```

This may have been asked [before](https://stackoverflow.com/questions/7425854/scala-create-val-for-outer-scope), but I wonder if there is an elegant solution that uses Option[A].

Answer: 
Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use `foldLeft` in order to simplify it:

```
val myOptimizedList = (1 to 100).foldLeft (myList) {
    case (list, 5) => optimize(list)
    case (list, _) => process(list); list
}

```
You can almost always rewrite some sort of looping construct as a (tail) recursive function:

```
@annotation.tailrec def processLists(xs: List[A], start: Int, stop: Int) {
  val next = start + 1
  if (start < 5) { process(xs); processLists(xs, next, stop)
  else if (start == 5) { processLists( optimize(xs), next, stop) }
  else if (start <= stop) { process(xs); processLists( xs, next, stop ) }
}
processLists(myList, 100, 1)

```

Here, you pass forward that data which you would otherwise have mutated. If you need to mutate a huge number of things it becomes unwieldy, but for one or two it is often as clear or clearer than doing the mutation.