245

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.

4
  • 2
    Well well, it seems like data.head worked... But still that only gives me first element, not any one in the list. Feb 13, 2011 at 0:53
  • Use the Seq traits apply(index) if you are sure the index is not out of bounds. scala-lang.org/api/current/…
    – Beezer
    Jun 23, 2016 at 19:10
  • data.drop(i).head works for accessing i-th element
    – Vinay
    Apr 16, 2017 at 3:54
  • @Vinay That is a costly operation. So one should avoid "drop(i).head". Oct 3, 2017 at 5:53

4 Answers 4

365

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

7
  • 1
    Basically I'm looking for something like ArrayList in java. I guess immutable would be fine too. Feb 13, 2011 at 1:00
  • 1
    ArrayBuffer works like ArrayList. Vector works like an immutable ArrayList--you can read, but you can't write without creating a new one.
    – Rex Kerr
    Feb 13, 2011 at 1:05
  • How about a subList? For example in java I do "data.subList(0, index)". Feb 13, 2011 at 2:27
  • Nevermind, I got it - it's "slice"! Can I convert ArrayBuffer to Vector? Or is there a more generic type I can return from methods? For example in Java I would return List interface. Feb 13, 2011 at 3:31
  • 1
    You can convert ArrayBuffer to an IndexedSeq using .toIndexedSeq; IndexedSeq is the more generic type. (In this case it actually turns out to be implemented as a Vector.) IndexedSeq is the supertype of collections that are reasonable to index into. Also, note that you could do Vector() ++ myArrayBuffer, which will work for almost any collection (on either side). ++ builds a new collection from the two you specify, preserving the type of the one on the left. Vector() is the empty vector, so it would produce what you want.
    – Rex Kerr
    Feb 13, 2011 at 3:36
151

Safer is to use lift so you can extract the value if it exists and fail gracefully if it does not.

data.lift(2)

This will return None if the list isn't long enough to provide that element, and Some(value) if it is.

scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None

Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.

Explanation:

This works because List's apply (which sugars to just parentheses, e.g. l(index)) is like a partial function that is defined wherever the list has an element. The List.lift method turns the partial apply function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.

2
  • 17
    Lift is beautiful. I can avoid arrayIndexOutOfBound errors, without checking size of array.. Mar 27, 2017 at 6:09
  • 1
    The opposite of a "partial" function (only defined for some input, not all) is a "total" function (defined for all input). What you call a "normal" function is technically called a "total" function. The inferred apply as in l(1) [which is really just shorthand for l.apply(1)] in your example is a partial function. The function l.lift(1) is a total function. Wrapping any partial function in an Option (or Try or Either) makes it a total function. Aug 23, 2020 at 20:37
11

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). 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. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)
4

Please use parentheses () to access the list of elements, as shown below.

list_name(index)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.