简体   繁体   English

Scala错误:尝试修改内容时出现“重新分配给val”?

[英]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 ... 我不是要更改引用byRef,而是要更改其内容...

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. case类参数被隐式声明为val并被视为类字段,这就是为什么编译器不允许更改其值的原因。

Instead of changing it's value you should use copy method. 不应更改其值,而应使用copy方法。 Something like: 就像是:

byRef.copy(y = 5)

Case classes by default are immutable . 默认情况下,案例类是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 : 这是实现用例和OP答案的最简单方法,即我需要将用例类属性标记为var

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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