Skip to content

Instantly share code, notes, and snippets.

@khongi
Created April 26, 2019 15:14
Show Gist options
  • Save khongi/726409b10072cf3152a71af548489d41 to your computer and use it in GitHub Desktop.
Save khongi/726409b10072cf3152a71af548489d41 to your computer and use it in GitHub Desktop.
Solution to The Dog Riddle
sealed class Animal {
object Cat: Animal()
}
class Dog(breedParam: String) : Animal() {
private constructor() : this("")
val breed: String? = if (breedParam == "") null else breedParam
companion object {
val Dog = Dog()
}
}
import Animal.Cat
import Dog.Companion.Dog
fun main() {
val cat: Animal = Cat
val dog: Animal = Dog
val husky: Animal = Dog("husky")
val emptyDog: Animal = Dog() // error
val nullDog: Animal = Dog(null) // error
val opinion = when (val animal = getAnimal()) {
is Cat -> {
"Cat"
}
is Dog -> {
if (animal.breed == null)
"Generic Dog"
else
"Specific dog: ${animal.breed}"
}
}
println(opinion)
val labrador = Dog("labrador")
val corgi = Dog("corgi")
println(labrador.breed) // labrador
println(corgi.breed) // corgi
}
fun getAnimal(): Animal {
return Dog("golden retriever")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment