Global Variables in Scala
Your example should work fine. If there's a problem, it doesn't seem to be in the code you've posted. As a side note, your myDict
does not need to be a var
since you don't want to re-assign it. The var
and val
keywords in Scala refer not to the referenced object or class instance, but to the reference, for example:
val x = 5
x = 6 // This will fail, reassignment to val
var y = 3
y = 5 // This works
val z = mutable.Map[String,String]()
z.put("foo", "bar") // This works because the reference is not modified
z = mutable.Map[String,String]() // This fails
Here's how you test your Scala_Object
on the Scala console:
scala> :paste
// Paste the code of your Scala_Object here
// And press Ctrl-D
defined module Scala_Object
scala> Scala_Object.myDict
res1: scala.collection.mutable.Map[String,String] = Map()
scala> ScalaObject.str_rev("foo")
res4: String = oof
scala> ScalaObject.myDict
res5: scala.collection.mutable.Map[String,String] = Map(foo -> oof)
scala> ScalaObject.str_rev("lol")
res6: String = lol
scala> ScalaObject.myDict
res7: scala.collection.mutable.Map[String,String] = Map(lol -> lol, foo -> oof)
Related videos on Youtube
Learner
Updated on May 25, 2022Comments
-
Learner over 1 year
I'm new to Scala and functional programming for that matter. I'm trying to use the functionality of global variables inside my main() functions like this,
object Scala_Object { var myDict = scala.collection.mutable.Map[String,String]() def str_rev(s : String) : String = { myDict.put(s,s.reverse) return (s.reverse) } def main (args: Array[String]){ .. .. val result = parsedArray.map(line => line.map { word => if( word == "") word else if(word == line(2) || word == line(3)) str_rev(word) else if ( word == line(1) || word == line(26)) str_rev(word) else word}) }
At the end of my program only elements from my first line from parsedArray( which is an
Array[Array[String]]
) is added to the dict - myDict. Is there anything that I'm missing ? I noticed that there isn't doc/tutorial on Global variables, so I presume there is fundamentally No concept called Global variables in SCALA. Then, how is the concept of global variables handled in Scala ?-
fresskoma about 10 yearsPlease try to improve your code formatting next time :) It was kind of hard to read.
-
Madoc about 10 yearsYour
myDict
is a global variable. It can be referenced by other classes asScala_Object.myDict
. And in a wayScala_Object
is a global variable too.
-