Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Scala for loop modify variables outside its scope?

Tags:

scala

For example suppose I have the following

  var lastSecurity = ""

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

At the moment

lastSecurity = security

Seems to be creating a new variable in scope rather than modifying the variable declared in the first line of code.

like image 437
deltanovember Avatar asked Dec 22 '22 10:12

deltanovember


2 Answers

Try this:

var lastSecurity = ""

def allSecurities = for {
  security <- lastTrade.keySet.toList
} yield {
  lastSecurity = security
  security
}
like image 72
missingfaktor Avatar answered Feb 16 '23 06:02

missingfaktor


It's just like

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

which prints

2
1

It doesn't matter whether these are vars or vals. In Scala you're allowed to shadow variables from the outer scope, but this might lead to some confusion when you're exscused having to use the val keyword, i.e. for-comprehensions, anonymous functions and pattern matching.

like image 35
Luigi Plinge Avatar answered Feb 16 '23 08:02

Luigi Plinge