I found some surprising compiler/IDE behavior that I’d like to understand.
I had this working code:
listOfPairs
.filter { it.first is Banana }
.map { (banana, foo) ->
banana as Banana
eat(banana)
I got a review comment, suggesting this:
listOfPairs
.filterIsInstance<Pair<Banana,Foo>>()
.map { (banana, foo) ->
eat(banana)
Looks nice, doesn’t need the
as Banana
part, but it crashes with a class cast exception on the
.map
line, because
Apple can't be cast to Banana
.
Why is that and why does it compile? I guess that the “reified” generics from the
.filterIsInstance
inline function only go one level deep, so it checks only for
Pair
, not
Pair<Banana, Foo>
? If that’s the case, it shouldn’t even compile if I specify <Banana, Foo>. Or what is going on here?