Variable scope not getting


#1

Hi ,

I have declared empty variable s, within db.run, i am concatenating some values from database, if I print , I get the values but when i return s i am getting empty

I am getting output like this

Colombian 101 7.99 0 0

Colombian 101 7.99 0 0
Colombian_Decaf 101 8.99 0 0

Colombian 101 7.99 0 0
Colombian_Decaf 101 8.99 0 0
Espresso 150 9.99 0 0

Colombian 101 7.99 0 0
Colombian_Decaf 101 8.99 0 0
Espresso 150 9.99 0 0
French_Roast 49 8.99 0 0

Colombian 101 7.99 0 0
Colombian_Decaf 101 8.99 0 0
Espresso 150 9.99 0 0
French_Roast 49 8.99 0 0
French_Roast_Decaf 49 9.99 0 0

It is not returning concatenated s, it is returning initial empty s

can anyone help me to get modified s

Thank you


#2

DB.run runs on a separate thread. So by the time the computation is over and ‘s’ is updated with new value, you have already returned the ‘s’. Instead of returning String you could return Future[String]. Your function signature would then become

def queryCoffee : Future[String] = {
...
}

#3

This is great example of why you should strive to avoid the use of var in Scala. In general, in all programming languages, your programs will be more robust and easy to reason about if the data is always constant. In imperative languages, they often don’t provide good mechanisms for doing this or make it very hard to do this. However, in Scala it is reasonably easy to start with. When you start off, don’t use var and don’t use mutable collections. That will get rid of most of the mutation that would happen in your programs.

Now there might be times when you feel that the solution to a problem is better with a var or other mutable data. There are times when that is the case. This is something I also like about Scala and it doesn’t assume that any one approach is the absolute right way to do things. However, you really should think about how and why you are using mutable memory to make sure that it is safe, especially when your program is involving multiple threads.