Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item in the list in Scala?

Tags:

scala

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.

like image 600
Andriy Drozdyuk Avatar asked Feb 13 '11 00:02

Andriy Drozdyuk


People also ask

How do I access elements in Scala list?

Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call.

How do you check if a value is in a list Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element. Otherwise, it returns false .

How do I return a list in Scala?

Scala List Methods. head: This method returns the first element of the scala list. tail: This method returns all the elements except the first. isEmpty: This method checks if the list is empty in which case it returns True else False.


1 Answers

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

like image 106
Rex Kerr Avatar answered Sep 28 '22 23:09

Rex Kerr