Skip to content

Instantly share code, notes, and snippets.

@deeperunderstanding
Last active November 13, 2019 16:17
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 deeperunderstanding/b373416e45a38586b95c01ee72f82ab7 to your computer and use it in GitHub Desktop.
Save deeperunderstanding/b373416e45a38586b95c01ee72f82ab7 to your computer and use it in GitHub Desktop.
fun toPet(values: List<String>): Try<Pet> {
val name = values[0]
val ageTry = Try { values[1].toInt() }.recoverWith { Failure<Int>(Exception("Cannot extract age!")) }
val typeTry = PetType.lookup(values[2]).recover { PetType.Invalid }
return ageTry.flatMap { age -> typeTry.map { type -> Pet(name, age, type) } }
}
enum class PetType(val type: String) {
Cat("Cat"),
Dog("Dog"),
Ferret("Ferret"),
Invalid("");
companion object {
val mapping = PetType.values().associateBy(PetType::type)
fun lookup(type: String) = Try { mapping[type] ?: throw Exception("No Pet Type: $type") }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment