rednifre
07/09/2024, 2:37 PMlistOfPairs
.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?ephemient
07/09/2024, 2:49 PM.filterIsInstance<Pair<Banana,Foo>>()
is similar to
.filter { it is Pair<Banana,Foo> }
(with an improved return type)ephemient
07/09/2024, 2:50 PMit is Pair<*,*>
ephemient
07/09/2024, 2:50 PM.filterIsInstance
is unable to show the warning due to other compiler limitationsrednifre
07/09/2024, 2:54 PM.filter { it is Pair<Banana,Foo> }
Is there an easy to remember rule for which functions don’t give compile errors because of compiler limitations?efemoney
07/11/2024, 5:56 AM