remove Unless Instance Of
Removes any items in the list that are not type A and returns a MutableCollection<A> with the remaining items.
The mutable equivalent to Collection.filterIsInstance.
Note: this function removes in-place only if A is a MutableList, otherwise it clears the collection and re-adds the values.
Removes any items in the list that are not type A and returns a MutableList<A> with the remaining items.
The mutable equivalent to List.filterIsInstance.
sealed interface Item {
data class SoldOut(val name: String) : Item
data class Available(val name: String, val remaining: Int) : Item
}
data class Catalog(val items: List<Item>)
fun filterAvailable(catalog: Catalog) =
catalog.copy {
items.removeUnlessInstanceOf<Item.Available>()
}
Content copied to clipboard
The returned value is a typed mutable collection where we can do further modifications with the right type, saving you having to do further type checks.
items.removeUnlessInstanceOf<Item.Available>()
.mutateAll { item -> item.remaining-- }
Content copied to clipboard
Removes any items in the list that are not type A and returns a MutableSet<A> with the remaining items.
The mutable equivalent to Set.filterIsInstance.