Get item in the list in Scala?

Andriy Drozdyuk picture Andriy Drozdyuk · Feb 13, 2011 · Viewed 241.6k times · Source

How in the world do you get just an element at index i from the List in scala?

I tried get(i), and [i] - nothing works. Googling only returns how to "find" an element in the list. But I already know the index of the element!

Here is the code that does not compile:

def buildTree(data: List[Data2D]):Node ={
  if(data.length == 1){
      var point:Data2D = data[0]  //Nope - does not work

  }
  return null
}

Looking at the List api does not help, as my eyes just cross.

Answer

Rex Kerr picture Rex Kerr · Feb 13, 2011

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).