无法修改Seq.head

时间:2017-08-23 11:45:54

标签: scala

我正在学习Scala,并对Seq.head感到困惑。

scala> x = Array(1, 2, 3)
x: Array[Int] = [I@545e9f15

scala> x
res64: Array[Int] = Array(1, 2, 3)

scala> x(0)
res65: Int = 1

scala> x.head
res66: Int = 1

scala> x(0) += 1

scala> x.head += 1
<console>:13: error: value += is not a member of Int
       x.head += 1
              ^

scala> x.head = 1
<console>:12: error: value head_= is not a member of scala.collection.mutable.ArrayOps[Int]
       x.head = 1
         ^

scala>

似乎在下面发生了一些隐含的约定。

但是从Scala API开始,Array.head的类型是Int(在我的例子中):

def head: T

那为什么我可以修改这个元素呢?

2 个答案:

答案 0 :(得分:2)

您问题的主要区别在于x(0) += 1(有效)和x.head += 1(无效)。

x(0) += 1相当于x(0) = x(0) + 1,这是x.update(0, x.apply(0) + 1)的语法糖。该指令增加了x(0)的值。

x.head返回Int,这是不可变的,因此x.head += 1失败。

答案 1 :(得分:1)

我相信documentation的摘录可能有用:

  

val numbers = Array(1, 2, 3, 4)

     

val first = numbers(0)

     

numbers(3) = 100

     

阵列使用两种常见的Scala复合糖片,如图所示   在上面的示例代码的第2行和第3行。第2行被翻译成   应用(Int)的调用,而第3行被转换为调用   更新(Int,T)。

当您在赋值的左侧使用括号时,它们将转换为替换数组中元素的更新调用。 .head方法没有这样的转换,它只是获取第一个元素的一种方法,因此您无法使用它来修改列表。