Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

while loop - Assign a value based on if condition in Scala

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please read this article read

You should use var instead of val. If you use val, this value cannot be used except in the if scope.

var i = 0
var magicValue = 0
while (i < 5){
  if(i==2) magicValue = i
   i += 1
}
println(magicValue)

demo

Each variable declaration is preceded by its type.
By contrast, Scala has two types of variables:
val creates an immutable variable (like final in Java)
var creates a mutable variable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...