Smart casting inside List::filter


I absolutely love the smart casting of Kotlin, it’s been really helpful, but there are some things I wish it did. Now, I’m not sure if it’s possible, but when filtering a list for only type (say) String, could Kotlin smart cast the returned list to be a list of Strings?

list.filter {it is String}
    .forEach {println(it.length)}

To be fair, that specific example could be done by simply be done by ignoring the filter step, but that’s just to give an idea of what I was referencing. This way, if we have a list (say from a library) that could return multiple types of objects, we could filter by the type we wanted to deal with, and then smart casting would prevent us from having to say “is String” every time we wanted to use it in the rest of the loops.


Having the compiler figure this out automatically seems way out of reach, but there is a method for this concrete use case: list.filterIsInstance<String>()


Yeah, that was my one concern, that it would be a lot… :l

I guess the list.filterIsInstance() will suffice for this specific case, still, there are areas this wouldn’t work. If it wouldn’t be too difficult, I feel it would be a neat addition to the smart casting aspect of Kotlin. Thanks for the alternative!


It would be super difficult, and way beyond smart casts.