Skip to content

Instantly share code, notes, and snippets.

@deeperunderstanding
Last active November 25, 2019 15:33
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/44dae57cc219bfd086078b8e97080596 to your computer and use it in GitHub Desktop.
Save deeperunderstanding/44dae57cc219bfd086078b8e97080596 to your computer and use it in GitHub Desktop.
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