cool breeze cool breeze - 4 months ago 16
Scala Question

How to safely split a string and check for both values

If I do this it throws an exception:

"".split('=')(1)


Is there a idomatic way to do this kind of operation safely in scala?

Answer
scala> "".split('=').lift(1)
res0: Option[String] = None

scala> "a=b".split('=').lift(1)
res2: Option[String] = Some(b)

Note that Array after implicit conversion is a partial function from indices to values. You can lift any partial function, so that instead of a value, or an exception if it is not defined at the given argument, it will return Some(value) or None respectively.