I wrote this simple program ( I pass Map from String to Int to method as a parameter) and it seems that is passing it by reference. How do I make it pass by Value?
import scala.collection.immutable._
import scala.io.Source._
/**
* Created by Alex on 5/11/16.
*/
object ScalaPassByValue {
type Env = scala.collection.mutable.Map[String,Int]
def mt_env : Env = {
scala.collection.mutable.Map.empty[String,Int]
}
def extend_env (sym: String, v: Int, env: Env) : Env = {
if(env.contains(sym)) {
env(sym) = v
env}
else {
env += (sym -> v)
env}
}
def main(args: Array[String]): Unit = {
bar(mt_env)
}
def bar (env: Env) : Unit = {
println("In A")
extend_env("a", 666,env)
print_env(env)
bullshit2(env)
bullshit3(env)
}
def bar2 (env: Env) : Unit = {
println("In AB")
extend_env("b", 326,env)
print_env(env)
}
def bar3 (env: Env) : Unit = {
println("In AC")
extend_env("c", 954,env)
print_env(env)
}
def print_env(env: Env) : Unit = {
//println("Environment")
for ((k,v) <- env){
v match {
case value: Int => print("Arg: "+k+" = ")
print(value+"\n")
case _ =>
}
}
}
}
Ideally I want main method to pass empty map to method bar which would add a map from 'b' to 666, then call two method to add 'b' and 'c' respectively. At the end I want to get printed
In A
Arg: a = 666
In AB
Arg: a = 666
Arg: b = 326
In AC
Arg: a = 666
Arg: c = 954
but get this:
In A
Arg: a = 666
In AB
Arg: b = 326
Arg: a = 666
In AC
Arg: b = 326
Arg: a = 666
Arg: c = 954
How can I make Scala pass my Map by value so modification in call to bar2 doesn't modify original map