cool breeze cool breeze - 1 year ago 83
Scala Question

How to safely split a string and check for both values

If I do this it throws an exception:


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

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download