Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 354
Loic Avatar asked Apr 26 '13 07:04

Loic


People also ask

How do you get the index of an element in a list in Scala?

Scala List indexOf() method with example. The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Return Type: It returns the index of the element present in the argument.

How do I append to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.

What is the difference between Array and list in Scala?

Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.

How do you define a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.


1 Answers

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
like image 127
drexin Avatar answered Oct 04 '22 22:10

drexin