Hello, why is there no autocast in this case? Seem...
# announcements
g
Hello, why is there no autocast in this case? Seems like a bug to me
Copy code
open 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
}
a
What cast do you expect?
g
Cast to a Dog
Nope, if it's not, it won't get past second condition
@Andrew S
a
Are you saying that the editor informs you there is no cast necessary, but actually it is necessary?
a
you have incorrect branching, remove
else if
and use
if
instead
else if
might never happen, so compiler can't guarantee than
animal
is always a
Dog
imagine that first "if" has
print("Empty")
instead of
return
g
Yeah, but that's different case
a
Well, yeah, but it's too much for current smartcasting algorithm
The situation you're describing is not a bug, it's just not implemented (and probably won't be in the nearest future, I think)
1
a
You could argue that it's a bug in IntelliJ if IntelliJ shows that "No cast needed" though
a
Actually, there is no cast needed. I ran your code fine, without a cast, and it worked as expected. The autocomplete for
bark()
did not work, however:
Copy code
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()

    }
Output from this:
Copy code
val numbers = arrayOf(1, 2, 3)
foo(numbers, Dog())
Is this:
Copy code
AppKt$main$Dog@3f99bd52
AppKt$main$Dog@3f99bd52
Huf huf!
So the smart casting seems to work fine!