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.
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.
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 .
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.
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]
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With