def merge(
left: mutable.ListBuffer[CaseClass],
right: ListBuffer[CaseClass]
): ListBuffer[CaseClass] = {
leftData.dimList =
newDimVal.patch(index,Seq(rightData.dimList(index)),0)
here i am getting Reassignment to val issue where leftData.dimList and newDimVal both are ListBuffer
CodePudding user response:
val
s in Scala are for immutable references. If you want to be able to reassign, you have to declare dimList
as a var
.
val a = 4
var b = 2
b = 7 // works
a = 3 // doesn't compile, citing a reassignment to val
Note that if leftData
is a case class
, its members are implicitly val
s if you don't specify it differently. However, case class
es should be used exclusively for immutable data.
CodePudding user response:
The lang already has simple ways to merge mutable\immutable collections.
Case Classes are Good for Modeling Immutable Data
You can’t reassign leftData.dimList
because it is a val (i.e. immutable). It is possible to use vars in case classes but this is discouraged.
See the docs.
Iterable Collections can be Zipped
The whole suite of zip
and unzip
methods are useful to merge or un-merge collections.
val xs = ListBuffer(1,2,3)
val ys = ListBuffer(3,4,5)
xs
.zip(ys)
.map { case (fromA, fromB) => /*merge logic*/ }
Note: Here you could swap ListBuffer
for immutable.List
. Zip creates a new instance.