Skip to content

Instantly share code, notes, and snippets.

@bastman
Created November 22, 2024 08:50
Show Gist options
  • Save bastman/9b4fbf98f4e10702add2d4612ac0ad8d to your computer and use it in GitHub Desktop.
Save bastman/9b4fbf98f4e10702add2d4612ac0ad8d to your computer and use it in GitHub Desktop.
kotlin: filterIsInstance for a subclass/instance of a sealed class
/**
* Filters the elements of this list to be instances of the specified type parameter [Child].
*/
public inline fun <reified T, reified Child : T> Iterable<T>.filterIsSubClassInstanceOf(): List<Child> {
return this.filterIsInstance<Child>()
}
// usage example ...
sealed class S {
object A : S()
object B : S()
object C : S()
}
fun foo() {
val source:List<S> =listOf(S.A, S.B, S.C)
val outcome:List<S.A> =source.filterIsSubClassInstanceOf()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment