Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an option when reading a vector

Tags:

scala

Reading from a vector, I want to return none when trying to read an index that is out of bounds and some otherwise. Is there a standard method for this?

like image 985
Spencer Booth Avatar asked Oct 28 '14 20:10

Spencer Booth


1 Answers

You can use lift:

val v = Vector(1, 2, 3)
v.lift(0)  //Some(1)
v.lift(5)  //None

note this works for any partial function.

like image 64
Lee Avatar answered Nov 04 '22 06:11

Lee