I came across this unusual behavior. The output of...
# random
I came across this unusual behavior. The output of line 23 is
Foo's ext
, whereas the output of line 24 is
Bar's ext
. I was under the impression that
foo as? Bar ?: foo
was effectively the same type inference logic as
if (foo is Bar) foo else foo
. Can someone shed some light on the differences here?
For the record, since Ben and I figured this out, here’s the issue:
(foo as? Bar).ext()) ?: foo.ext()
would have been the same as
if (foo is Bar) foo.ext() else foo.ext()
The issue is with doing
(foo as? Bar ?: foo).ext()
. Even though foo gets smart-cast to Bar, it gets downcast again to fit with the upper bound of Foo again. And because extension functions are statically dispatched, which function is executed gets decided at compile time. Foo.ext() is chosen over Bar.ext().
💯 1
🔥 1