Convert a String with comma separated latitudes and longitudes to a Seq[Coordinate] I have a function that receives a String like the following:

"-10.0 -10.0,10.0 10.0,0.0 0.0"


And needs to translate that into a Seq[Coordinate] that would look like this:

Seq(
    Coordinate(-10.0, -10.0),
    Coordinate( 10.0,  10.0),
    Coordinate(  0.0,   0.0)
)


Here is the function that I wrote to achieve this:

def toCoordinates(coordinates: String): Seq[Coordinate] = {
  val coordinatesList = coordinates.split(",")
  coordinatesList flatMap { coordinate =&gt;
    coordinate.split("\\s+") match {
      case Array(lat:String, lon:String) =&gt; Some(Coordinate(lat.toDouble, lon.toDouble))
      case _                             =&gt; None
    }
  }
}


I see that if someone sends "foo bar" as a coordinate, my code would fail miserably, although I don't see a way to prevent this without some if conditions.

Any idea on how I can implement this check while still having functional code? Or any other tips that might be helpful for a Scala newbie.
Also you can write more human-readable and understandable algorithm with the help of extractors and method collect:

val Coord = """(.+?)\s+(.+)""".r

object Double { def unapply(s: String) = Try(s.toDouble).toOption }

def parseCoordinates(input: String): Seq[Coordinate] =
  input.split(',') collect {
    case Coord(Double(lat), Double(lan)) =&gt; Coordinate(lat, lan)
  }