Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 更新声明为val的字段_Scala - Fatal编程技术网

Scala 更新声明为val的字段

Scala 更新声明为val的字段,scala,Scala,我在参加的在线课程中看到了这个类的定义: class Img(val width: Int, val height: Int, private val data: Array[Int]) { def this(w: Int, h: Int) = this(w, h, new Array(w * h)) def apply(x: Int, y: Int): Int = data(y * width + x) def update(x: Int, y: In

我在参加的在线课程中看到了这个
类的定义:

   class Img(val width: Int, val height: Int, private val data: Array[Int]) {
      def this(w: Int, h: Int) = this(w, h, new Array(w * h))
      def apply(x: Int, y: Int): Int = data(y * width + x)
      def update(x: Int, y: Int, c: Int): Unit = data(y * width + x) = c
    }
我很困惑。即使声明为
val
,我们如何像这样更新
data(y*width+x)=c


这是一种更广泛使用的模式吗?

val
表示不能更改曾经分配给
数据的值。此值是对数组的引用,因此
数据
将始终指向同一数组,但数组本身是可变的,您可以随时更改其内容。

val
表示您不能更改曾经分配给
数据
的值。此值是对数组的引用,因此
数据
将始终指向同一数组,但数组本身是可变的,您可以随时更改其内容。

这有点像Java中的
final int[10]data
。您不能更改引用,但可以更改它的内容,如果它是可变的,在本例中就是可变的。这有点像Java中的
final int[10]data
。您不能更改引用,但可以更改它的内容,如果它是可变的,在本例中是可变的。