Reputation: 1591
Is there any simple way to split safely by avoiding index bound of exception?
For example:
"1-2".split("-")(1) == "2"
"1".split("-")(1) == null
Upvotes: 3
Views: 2500
Reputation: 5093
This functionality is already implemented in Array
. lift
method returns None
for an out of bounds index, otherwise it returns Some(value)
val array = Array(3, 5, 1)
array.lift(5) // None
array.lift(0) // Some(3)
Upvotes: 15
Reputation: 2280
You can wrap your Operation using scala.util.Try
and then do getOrElse
over it. If the value at that index exists it will return that value else it will return the value specified in getOrElse
. Try following code for your above given scenario.
scala.util.Try("1".split("-")(1)).getOrElse(null)
//output
null
Upvotes: 3
Reputation: 10681
Scala Array doesn't provide safety method to get element by index. So you should consider IndexOutOfBoundsException
. Possible ways:
use Try
and test it if success:
scala.util.Try(array(index))
add own method:
implicit class RichArray[A](array: Array[A]) {
def opt(index: Int): Option[A] =
if (array.length < 0 || array.length <= index) None
else Some(array(index))
}
val array = Array(12, 3, 4)
array.opt(2) // Some(4)
array.opt(3) // None
Upvotes: 3