SkyWalker
SkyWalker

Reputation: 14309

Scala error: "reassignment to val" while attempting to modify content?

I have the following code that reveals the problem:

case class Best[T](x: Array[T], y: Double)

def someFunc(byRef : Best[Int]) : Unit = {
   byRef.y = 5
}

and I get the error:

Multiple markers at this line:

reassignment to val
reassignment to val

why is that? I am not attempting to change the reference byRef but its content ...

Upvotes: 0

Views: 1378

Answers (3)

SkyWalker
SkyWalker

Reputation: 14309

This is the simplest way to achieve my use-case and the answer to my OP i.e. what I needed is to mark the case class attributes as var:

case class Best[T](var x: Array[T], var y: Double)

def someFunc(byRef : Best[Int]) : Unit = {
   byRef.y = 5
}

Upvotes: 1

vvg
vvg

Reputation: 6385

Case classes by default are immutable. You can not change it's content. Instead you can create new case class with modified content:

case class Best[T](x: Array[T], y: Double)

def someFunc(byRef : Best[Int]) : Best[Int] = {
   byRef.copy(y = 5)
}

To achieve what you need - introduce mutability via simple classes. Not recommended

  class Worst[T](x: Array[T], var y: Double) {
    override def toString: String = s"$y:${x.toList}"
  }

  def someFunc2(byRef : Worst[Int]) : Unit = {
    byRef.y = 5
  }

  val w = new Worst(Array(1), 1)
  someFunc2(w)
  println(w)

Upvotes: 1

justAbit
justAbit

Reputation: 4256

case class arguments are implicitly declared as val and are treated as class fields that's why compiler does not allow to change it's value.

Instead of changing it's value you should use copy method. Something like:

byRef.copy(y = 5)

Upvotes: 3

Related Questions