I would like know how I can return a data class from a list of sealed classes. For example, I have :
data class Payroll(
val items: List<Inventory>
)
sealed class Inventory {
data class testOne(val amount: Int)
data class testTwo(val isProd: Boolean)
}
I would like to return testTwo class so I can perform a check on isProd.
I tried:
payroll.items.find{ it is Inventory.testTwo}
it returns TestTwo but as an Inventory so I cannot access testTwo.isProd
CodePudding user response:
First of all, testOne and testTwo in your example do not subtype Inventory. I assume this is just a mistake when preparing the example for StackOverflow.
If you need to find the first testTwo item or null if there is none, you can do it like this:
payroll.items.firstNotNullOfOrNull { it as? Inventory.testTwo }
Or if you need to find all testTwo items:
payroll.items.filterIsInstance<Inventory.testTwo>()
