concept first element in category scala

appears as: first element
Get Programming with Scala

This is an excerpt from Manning's book Get Programming with Scala.

  • apply – The method apply takes the index of the element in a sequence to return. In Scala, indexes always start from zero: the first element will have index 0, the second one index 1, and so on. It is an impure function because it throws an instance of IndexOutOfBoundsException if no element is available for the given index.
  • scala> List(1,2,3).apply(0)
    res12: Int = 1
    // expression equivalent to List(1,2,3)(0)
     
    scala> List(1,2,3).apply(3)
    java.lang.IndexOutOfBoundsException: 3
      at scala.collection.LinearSeqOptimized.apply(LinearSeqOptimized.scala:63)
      ... 28 elided
    // expression equivalent to List(1,2,3)(3)
  • headOption – The function head, and its equivalent apply(0) are impure functions as they throw exceptions for empty sequences: the method headOption is their pure alternative. When selecting the first element in a list, it returns its first element wrapped in a Some if present, otherwise None if missing.