Let run with, also apply. Filter takeIf

It would be a terrible ambiguity if T?.filter { } meant something completely different from T.filter { } for certain T types:

val collection = listOf("foo", "bar", "")
var collection2: List<String>? = collection //type could be not so explicit

collection2 = collection2.filter { it.isNotEmpty() }
collection2 = collection.filter { it.isNotEmpty() }

Could you tell at glance which filter does what?

That’s why we had to find different names for the similar concept functions like filter/takeIf: to disambiguate the operation, because they can be used on the same receiver.

2 Likes