Home > front end >  Reassignment to val issue
Reassignment to val issue

Time:11-23

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:

vals 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 vals if you don't specify it differently. However, case classes 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.

  • Related