74

Is there a way, only using the Scala collection API, to get an Option in a List when trying to get an element by its index?

I'm looking for the equivalent of this function, does it exist?

def optionalValue[T](l: List[T], index: Int) = {
  if (l.size < (index+1)) None 
  else Some(l(index))
}

Thanks

giampaolo
  • 6,906
  • 5
  • 45
  • 73
Loic
  • 3,310
  • 4
  • 25
  • 43

1 Answers1

160

Yes, you can lift your collection to a function Int => Option[A]:

scala> List(1,2,3).lift
res0: Int => Option[Int] = <function1>

scala> List(1,2,3).lift(9)
res1: Option[Int] = None
drexin
  • 24,225
  • 4
  • 67
  • 81
  • 15
    I already saw `lift` for a lot of data-structure in Scala, what's the rationale behind the naming (and the abstraction)? – mutantacule Aug 08 '16 at 15:14
  • 9
    @kosii maybe a bit late with the answer, but in this case "lift" refers to the transformation from a partial function of type `Int => T` to a total function of type `Int => Option[T]`. It is quite a common term for transforming from something less general to something more general, or, in other words, "adding" a new structure, e.g. transforming a monad to a monad transformer, or transforming a functor to a free monad. I think the term came from the category theory, but I couldn't find any definite references. – Vladimir Matveev Nov 13 '17 at 18:03