Skip to content

Instantly share code, notes, and snippets.

@vaughandroid
Last active April 26, 2019 12:52
Show Gist options
  • Save vaughandroid/62a45dafc555046c26decdfcd1ae3f2c to your computer and use it in GitHub Desktop.
Save vaughandroid/62a45dafc555046c26decdfcd1ae3f2c to your computer and use it in GitHub Desktop.
Kotlin dog riddle solution
// We are modelling different types of animals.
sealed class Animal {
// Cats are simple. A cat is a cat.
object Cat : Animal()
sealed class Dog: Animal() {
companion object : Dog()
data class Breed(val breed: String) : Dog()
}
fun Dog(breed: String) = Dog.Breed(breed)
}
// Example usage
fun main() {
// All of these lines should work:
var animal: Animal
animal = Cat
animal = Dog
animal = Dog("husky")
// Implementation needs to work with an exhaustive when, such as this one:
val opinion = when (animal) {
is Cat -> {
"Cat"
}
is Dog -> {
if (animal.breed == null) "Generic dog" else "Specific dog: ${animal.breed}"
}
}
// This should NOT compile, as for a dog without a breed, we want just the `Dog` syntax.
Dog()
// This should not compile either, for the same reason.
Dog(null)
// Finally, different Dogs created are expected to have different breeds when checked later:
val animal1 = Dog("labrador")
val animal2 = Dog("husky")
println(animal1.breed) // labrador
println(animal2.breed) // husky
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment