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
}

```
There's another technique (perhaps trick in this case) to delay initialization of 
`myOptimizedList` which is to use a lazy val. Your example is very specific but the principal is still obvious, delay assignment of a val until it is first referenced.

```
val      myList          = List(A(), A(), A())
lazy val myOptimizedList = optimize(myList)

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

```

Note that the case `iteration == 5` is ignored.