1
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

That looks pretty good to me.

Try is preferable over try/catch since it gives more options on how to process the Failure case. In particular, the fact that Try can be flatMap'd means that you an build a for-comprehension to cover the processing and essentially abort on the first failure.

for {
  x <- Try("1".toInt)
  y <- Try("a".toInt)
  z <- Try("3".toInt)  // never invoked due to above error
} yield x + y + z

// returns: Failure(java.lang.NumberFormatException: For input string: "a")

For parsing a String to an Int it doesn't matter as much, but if the body of the Try is expensive then some of that cost can be avoided.

Depending on the context you're working in then it might behoove you to capture and log the Failures as well; for some one-off code silently ignoring the failures might be fine, but in an application it can save a lot of heartache when dirty data inevitably makes its way in.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.