Created
November 22, 2024 08:50
-
-
Save bastman/9b4fbf98f4e10702add2d4612ac0ad8d to your computer and use it in GitHub Desktop.
kotlin: filterIsInstance for a subclass/instance of a sealed class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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