简体   繁体   中英

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 ...

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)

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)

This is the simplest way to achieve my use-case and the answer to my OP ie 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM