【发布时间】:2015-10-04 19:51:52
【问题描述】:
嘿,我有以下代码:
var z:Array[String] = new Array[String](4);
z(0) = "Dave";
z(1) = "Joe";
z(2) = "Jim";
z.apply(3) = "Roger";
这里的最后一行给出了一个编译时错误——“在类 Array 中应用方法缺少参数;如果你想将其视为部分应用的函数,请在此方法后面加上 `_'”
这对我来说没有意义,因为我已经读到,当您将围绕另一个值的括号应用到变量时,Scala 会将代码转换为对该变量名为 apply 的方法的调用。 因此,如果以下行:
z(2) = "Jim";
转换成
z.apply(2) = "Jim";
那为什么行
z.apply(3) = "Roger";
给我一个编译时错误?
我是 Scala 的新手,所以任何帮助都会非常感谢!
【问题讨论】:
-
有趣的问题,因为
Array#applydocs 状态:Indices start at 0; xs.apply(0) is the first element of array xs. Note the indexing syntax xs(i) is a shorthand for xs.apply(i). -
你正在做的事情被去糖化到
update,而不是apply。update的文档类似:Indices start at 0; xs.update(i, x) replaces the ith element in the array. Note the syntax xs(i) = x is a shorthand for xs.update(i, x).
标签: arrays scala compilation