4

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.

deltanovember
  • 42,611
  • 64
  • 162
  • 244

2 Answers2

10

Try this:

var lastSecurity = ""

def allSecurities = for {
  security <- lastTrade.keySet.toList
} yield {
  lastSecurity = security
  security
}
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
1

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.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180