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 =>
coordinate.split("\\s+") match {
case Array(lat:String, lon:String) => Some(Coordinate(lat.toDouble, lon.toDouble))
case _ => 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.