I wrote this question asking about how to implement my error handling while still maintaining functional code and based on 200_success's very interesting note on the spaces, I decided to trim()
the String
first, but I wanted to avoid using try/catch
blocks and use more of Scala's specific features, so I thought of a solution with the Try
type:
private def tryParseDouble(value: String) = Try(value.toDouble)
def toCoordinates(coordinates: String): Seq[Coordinate] = {
val coordinatesList = coordinates.split(",")
coordinatesList flatMap { coordinate =>
coordinate.trim().split("\\s+").map(tryParseDouble) match {
case Array(Success(lat), Success(lon)) => Some(Coordinate(lat, lon))
case _ => None
}
}
}
Would this be an acceptable way to implement error handling? Or am I overthinking this and a simple try/catch
would be just as good?