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.
Try this:
var lastSecurity = ""
def allSecurities = for {
security <- lastTrade.keySet.toList
} yield {
lastSecurity = security
security
}
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 var
s or val
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With