Last active
November 13, 2019 16:17
-
-
Save deeperunderstanding/b373416e45a38586b95c01ee72f82ab7 to your computer and use it in GitHub Desktop.
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
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