scala map in a method argument can not add key-value -
in scala , how pass map method reference object can add key-value map. tried code, doesn't work.
var rtnmap = map[int, string]() def getuserinputs(rtnmap: map[int, string]) { rtnmap += (1-> "ss") //wrong here }
i understand, default, argument in method val, final in java, can provide safety. @ least should allow insert new entry. have idea ?
welcome functional programming
first of use case possible mutable map
. have using immutable map
because default available in scala. package scala.predef
default available in scala , don't need import default.
below code works excepted.
import scala.collection.mutable.map val gmap = map[int, string]() def getuserinputs(lmap: map[int, string]) = { lmap += (1-> "ss") }
below call change contents of gmap
getuserinputs(gmap)
here proof
scala> import scala.collection.mutable.map import scala.collection.mutable.map scala> | val gmap = map[int, string]() gmap: scala.collection.mutable.map[int,string] = map() scala> | def getuserinputs(lmap: map[int, string]) = { | lmap += (1-> "ss") | } getuserinputs: (lmap: scala.collection.mutable.map[int,string])scala.collection.mutable.map[int,string] scala> getuserinputs(gmap) res2: scala.collection.mutable.map[int,string] = map(1 -> ss) scala> gmap res3: scala.collection.mutable.map[int,string] = map(1 -> ss)
in last scala repl notice contents of gmap
. gmap
contains added item.
general code improvements
do not use mutable collections unless have strong reason using it.
in case of immutable collections new instance returned when operation change existing datastructure done. way existing data structure not change. in many ways. ensures program correctness , ensures called referential transparency (read it).
so program should ideally this
val gmap = map.empty[string, string] //map[string, string]() def getuserinputs(lmap: map[int, string]) = { lmap += (1-> "ss") } val newmap = getuserinputs(gmap)
contents added newmap
, old map not changed, stays intact. useful because code holding on gmap
, accessing gmap
need not worried changes happening underlying structure.(lets in multi-threaded scenarios, useful.)
keeping original structure intact , creating new instance changed state general way of dealing state in functional programming. important understand , practice this.
deprecated syntax , removed in scala 2.12
you declared function below
def getuserinputs(lmap: map[int, string]) { // no = here lmap += (1-> "ss") }
in above function definition there no =
after closed parenthesis. deprecated in scala 2.12. don't use because scala compiler gives misleading compilation errors function declaration syntax.
correct way this.
def getuserinputs(lmap: map[int, string]) = { lmap += (1-> "ss") }
notice there =
in syntax.
Comments
Post a Comment