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
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
i = 0
while i<5:
if (i==2):
magic_value = i
i += 1
print(magic_value) # prints 2
question from:
https://stackoverflow.com/questions/65952702/assign-a-value-based-on-if-condition-in-scala 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…