gcx11
01/20/2019, 1:26 PMopen class Animal
class Dog: Animal() {
fun bark() = println("Huf huf!")
}
class Cat: Animal()
fun main() {
val numbers = arrayOf(1, 2, 3)
foo(numbers, Cat())
}
fun foo(numbers: Array<Int>, animal: Animal) {
if (numbers.isEmpty()) {
return
} else if (animal !is Dog) {
return
}
println(animal) // no autocast here
}alex
01/20/2019, 1:32 PMgcx11
01/20/2019, 1:33 PMgcx11
01/20/2019, 1:42 PMgcx11
01/20/2019, 1:43 PMAndrew S
01/20/2019, 1:44 PMalex
01/20/2019, 1:44 PMelse if and use if insteadalex
01/20/2019, 1:45 PMelse if might never happen, so compiler can't guarantee than animal is always a Dogalex
01/20/2019, 1:45 PMprint("Empty") instead of returngcx11
01/20/2019, 1:46 PMalex
01/20/2019, 1:49 PMalex
01/20/2019, 1:50 PMAlowaniak
01/20/2019, 7:49 PMAndrew S
01/21/2019, 8:22 AMbark() did not work, however:
fun foo(numbers: Array<Int>, animal: Animal) {
if (numbers.isEmpty()) {
return
} else if (animal !is Dog) {
return
}
println(animal)
val dog = animal
println(dog)
dog.bark()
}Andrew S
01/21/2019, 8:27 AMval numbers = arrayOf(1, 2, 3)
foo(numbers, Dog())
Is this:
AppKt$main$Dog@3f99bd52
AppKt$main$Dog@3f99bd52
Huf huf!
So the smart casting seems to work fine!