Skip to content

Instantly share code, notes, and snippets.

@zsmb13

zsmb13/Animal.kt Secret

Last active May 3, 2019 15:14
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 zsmb13/8a373f098a7468a3ea609cf9a63e6769 to your computer and use it in GitHub Desktop.
Save zsmb13/8a373f098a7468a3ea609cf9a63e6769 to your computer and use it in GitHub Desktop.
DM me solutions on Twitter (@ zsmb13), or, even better, on the Kotlin Slack (zsmb) ;)
// We are modelling different types of animals.
sealed class Animal {
// Cats are simple. A cat is a cat.
object Cat : Animal()
// Dogs are more complicated. They can either be "just a dog", in which case we want
// to refer to their type as `Dog`, or they can be of a specific breed, so we also
// want to be able to use the `Dog("labrador")` syntax.
// TODO: the Dog implementation
// Note that no classes should be `open` in the solution. We want a sealed hierarchy.
}
// 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
}
@pro100svitlo
Copy link

what about next code?

class Dog : Animal {
      val breed: String?

      constructor() : super() {
        breed = null
      }

      constructor(breed: String) : super() {
        this.breed = breed
      }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment