Yogesh
Yogesh

Reputation: 99

Reassignment to val issue

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

Upvotes: 1

Views: 1125

Answers (2)

stefanobaghino
stefanobaghino

Reputation: 12804

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.

Upvotes: 2

gatear
gatear

Reputation: 946

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.

Upvotes: 1

Related Questions