-1

Actually I have this data class where data is a mutableList ,

data class DataTable (
    var total: Long = 0,

    @JsonProperty("data")
    var data: MutableList<Any>? = null )

my idea is that when that data arrives I can map it to a very important entity as I could do and tried to do this

 val summaryOrder2= dataTable.data as  MutableList<SummaryOrder>
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
dasuma
  • 781
  • 1
  • 6
  • 12

2 Answers2

0

What is the issue with casting the list?

Another way you might be able to achieve this is to filter the instance

val summaryOrder2 = dataTable.data?.filterIsInstance<SummaryOrder>()
Damon Baker
  • 887
  • 7
  • 9
0

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
Roland
  • 22,259
  • 4
  • 57
  • 84