class Cat {
fun purr() = println("Purr purr")
}
// *** before: ***
fun petOld(animal: Any) {
val isCat = animal is Cat
if (isCat) {
// animal.purr() // <- Error: Any has no purr(),
// the check stored in a variable was forgotten
(animal as Cat).purr()
}
}
// *** in version 2.0: ***
// the K2 compiler became the default one and remembers the check
// that was saved into a variable
fun pet(animal: Any) {
val isCat = animal is Cat
if (isCat) {
animal.purr() // animal is smart cast to Cat
}
}
fun main() {
petOld(Cat())
pet(Cat())
}