Can a Scala variable for a loop modify variables outside its scope?

For example, suppose I have the following

var lastSecurity = "" def allSecurities = for { security <- lastTrade.keySet.toList lastSecurity = security } yield security 

At present

 lastSecurity = security 

It seems that you need to create a new variable in scope, and not change the variable declared in the first line of code.

+4
source share
2 answers

Try the following:

 var lastSecurity = "" def allSecurities = for { security <- lastTrade.keySet.toList } yield { lastSecurity = security security } 
+10
source

It's just like

 var a = 1 { var a = 2 println(a) } println(a) 

which prints

 2 1 

It doesn't matter if they are var or val s. In Scala, you are allowed to obscure variables from the outer scope, but this can lead to some confusion when you exscused should use the val keyword, that is, for understanding, anonymous functions, and pattern matching.

+1
source

Source: https://habr.com/ru/post/897161/


All Articles