2
votes

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):

  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]
                         ^
1
Leaving this here (though it's such a simple one!) because the title may lead someone else to find the cure. - akauppi

1 Answers

11
votes

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 apply may be omitted. Thus:

def f(i:Int) = l.apply((i + 1) % n)

or short

def f(i:Int) = l((i + 1) % n)

Note that apply and size on a List take time O(N), so if you need those operations often for large lists, consider using Vector instead.