Scala 编译器错误:“需要标识符但找到整数文字”。为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12876646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala compiler error: "identifier expected but integer literal found". Why?
提问by akauppi
The code is obvious, and I fail to see what's wrong with it.
代码很明显,我看不出它有什么问题。
object TestX extends App {
val l= List[String]( "a","b","c" )
val n= l.size
def f( i:Int )= l[(i+1)%n ]
}
Compiler output (Scala 2.9.2):
编译器输出(Scala 2.9.2):
fsc -deprecation -d bin src/xxx.scala
src/xxx.scala:11: error: identifier expected but integer literal found.
def f( i:Int )= l[(i+1)%n]
^
回答by 0__
Brackets [, ]in Scala are used to declare or apply type parameters. Getting an element in a sequence or array is the apply(index: Int)method where applymay be omitted. Thus:
括号[,]在 Scala 中用于声明或应用类型参数。获取序列或数组中的元素是可以省略的apply(index: Int)方法apply。因此:
def f(i:Int) = l.apply((i + 1) % n)
or short
或短
def f(i:Int) = l((i + 1) % n)
Note that applyand sizeon a Listtake time O(N), so if you need those operations often for large lists, consider using Vectorinstead.
请注意,apply并size在List需要时间O(N),所以如果你需要这些操作通常用于大型列表,请考虑使用Vector替代。

