Last active
November 25, 2019 15:33
-
-
Save deeperunderstanding/44dae57cc219bfd086078b8e97080596 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 main() { | |
val lines = Try { | |
File("./my-pets.csv").readLines().map { it.split(',') } | |
} | |
val pets : Try<List<Pet>> = lines.map { it.map(::toPet) } | |
when (pets) { | |
is Success -> println(pets.value) | |
is Failure -> println(pets.error) | |
} | |
} | |
fun toPet(values: List<String>): Pet { | |
val name = values[0] | |
val age = values[1].toInt() | |
val type = PetType.lookup(values[2]) | |
return Pet(name, age, type) | |
} | |
data class Pet( | |
val name: String, | |
val age: Int, | |
val type: PetType | |
) | |
enum class PetType(val type: String) { | |
Cat("Cat"), | |
Dog("Dog"), | |
Ferret("Ferret"); | |
companion object { | |
val mapping = PetType.values().associateBy(PetType::type) | |
fun lookup(type: String) = 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