Last active
August 29, 2015 13:57
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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