How to code it in idiomatic Scala?
scala
Solution
Two approaches I personally find a little nicer:
def pair(s: String) = s.split(":") match {
case Array(k, v) => Some(k.trim -> v.trim)
case _ => None
}
Or using Scala's handy regular expression extractors:
val Pair = """\s*([^\s:]+)\s*:\s*([^\s:]+)\s*""".r
def pair(s: String) = s match {
case Pair(k, v) => Some(k -> v)
case _ => None
}
But yeah, yours isn't that bad either.
Problem
Suppose I want to write a function `def pair(s:String):Option[(String, String)]` to convert a string into a key-value pair in Scala. The string should look like `"<key>:<value>"`. How would you correct the solution below ? ``` def pair(s:String) = { val a = s.split(":"); if (a.length == 2) Some((a(0).trim, a(1).trim)) else None } ```