How do I filter a list within an object for a class type in Kotlin?

Viewed 30

Say I have

patients = this.entry.filter { it.resource is Patient }.map { it.resource as Patient }

Basically I have an object Bundle, and inside bundle is a list of objects that can be of any type. I only want the type of Patient in this case.

Could I write an exnteison function that would just take Bundle.toXYZ() where toXYZ() would filter that list for all items of type Patient?

But I want to write this generically so it can work for many things.

I tried this, but had no luck

fun <T> Bundle.toXYZ(item: T): List<T> {
    this.entry.filter { it.resource is item }.map { it.resource as item }
}

It says that it cannot resolve item.

1 Answers

I struggled with this for awhile, and then figured it out almost as soon as I asked for help. This worked:

inline fun <reified R> Bundle.toTypedEntryList(): List<R> {
    return this.entry.map { it.resource }.filterIsInstance<R>()
}
Related