drozzy drozzy - 5 months ago 55
Scala Question

Get item in the list in Scala?

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

I tried

, and
- 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 Source

Use parentheses:


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]).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download