I have a while loop that needs to create an object based on a condition happening inside the loop. The code runs fine but the object is not available once the loop finishes.

I suspect I am missing something about how variable scope works in Scala.

If what I am trying is not possible, I would like to understand why and what the alternatives are.

This is a simple example

```scala
var i = 0

while (i < 5) {
    val magicValue = if (i==2) i
    i += 1
}

println(magicValue) // error: not found: value magicValue

```

This is how I would do it in python

```py
i = 0

while i<5:
    if (i==2):
        magic_value = i
    i += 1

print(magic_value) # prints 2

```