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
}

```
It's often the case that you can rework your code to avoid the problem. Consider the simple, and common, example here:

```
var x = 0
if(something)
  x = 5
else
  x = 6
println(x)

```

This would be a pretty common pattern in most languages, but Scala has a better way of doing it. Specifically, if-statements can return values, so the better way is:

```
val x = 
  if(something)
    5
  else
    6
println(x)

```

So we can make `x` a val after all.

Now, clearly your code can be rewritten to use all `val`s:

```
val myList:A = List(...)
for (iteration <- 1 to 5)
  process(myList)
val myOptimizedList = optimize(myList)
for (iteration <- 5 to 100)
  process(myOptimizedList)

```

But I suspect this is simply an example, not your real case. But if you're unsure how you might rearrange your real code to accomplish something similar, please show us what it looks like.