How to get an Option from index in Collection in Scala?

ScalaScala Option

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoicView Question on Stackoverflow
Solution 1 - ScaladrexinView Answer on Stackoverflow