Skip to content

Instantly share code, notes, and snippets.

@sam
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam/9399667 to your computer and use it in GitHub Desktop.
Save sam/9399667 to your computer and use it in GitHub Desktop.
Brainstorming how to localize error messages with scalautil.org's Or and Every.
package presentation.json
import org.scalautils._
import Accumulation._
case class ErrorMessage(message: String, parameters: Any*) {
override def toString = message.format(parameters: _*)
}
case class Person(name: String, age: Int)
def parseName(input: String): String Or One[ErrorMessage] = {
val trimmed = input.trim
if (!trimmed.isEmpty)
Good(trimmed)
else
Bad(One(ErrorMessage(""""%s" is not a valid name""", input)))
}
def parseAge(input: String): Int Or One[ErrorMessage] = {
try {
val age = input.trim.toInt
if (age >= 0) Good(age) else Bad(One(ErrorMessage(""""%s" is not a valid age""", age)))
}
catch {
case _: NumberFormatException =>
Bad(One(ErrorMessage(""""%s" is not a valid integer""", input)))
}
}
def parsePerson(inputName: String,
inputAge: String): Person Or Every[ErrorMessage] = {
val name = parseName(inputName)
val age = parseAge(inputAge)
withGood(name, age) { Person(_, _) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment