What you are showing is a cast... what you probably want is either a map
or filterIsInstance
.
Why is casting here a bad idea? Because generic type information is erased at runtime... you can even do mutableListOf<Apple>() as List<Orange>
and will probably be shocked at runtime ;-) (note: such casts are therefore also mentioned as "unchecked casts")
Why map
or filter
? Use map
if you need to transform the contents of the data
-list to those objects... Use filter
(or filterIsInstance
) to filter out all those entries that match your criteria/predicate.
You may want to look up the referenced documentation.
So the possible solutions demonstrated:
data?.filterIsInstance<SummaryOrder>()
data?.filterIsInstance<SomeTransformable>()
?.map { it.toSummaryOrder() /* or whatever makes those instances a SummaryOrder */ }
Some more recommendations:
- try to omit nullable list types (doesn't it suffice to have an empty or non-empty list?)
- try to omit
Any
as list type; otherwise you need to use filterIsInstance
for anything you do with it