Created
April 26, 2019 15:14
-
-
Save khongi/726409b10072cf3152a71af548489d41 to your computer and use it in GitHub Desktop.
Solution to The Dog Riddle
This file contains 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
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() | |
} | |
} |
This file contains 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
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