Global Variables in Scala

14,023

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)
Share:
14,023

Related videos on Youtube

Learner
Author by

Learner

Updated on May 25, 2022

Comments

  • Learner
    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
      fresskoma about 10 years
      Please try to improve your code formatting next time :) It was kind of hard to read.
    • Madoc
      Madoc about 10 years
      Your myDict is a global variable. It can be referenced by other classes as Scala_Object.myDict. And in a way Scala_Object is a global variable too.