diff --git a/app/src/main/java/org/schabi/newpipe/util/Either.kt b/app/src/main/java/org/schabi/newpipe/util/Either.kt new file mode 100644 index 000000000..9d1f8f0f2 --- /dev/null +++ b/app/src/main/java/org/schabi/newpipe/util/Either.kt @@ -0,0 +1,25 @@ +package org.schabi.newpipe.util + +import androidx.compose.runtime.Stable +import kotlin.reflect.KClass +import kotlin.reflect.cast +import kotlin.reflect.safeCast + +@Stable +data class Either( + val value: Any, + val classA: KClass, + val classB: KClass, +) { + inline fun match(ifLeft: (A) -> R, ifRight: (B) -> R): R { + return classA.safeCast(value)?.let { ifLeft(it) } + ?: ifRight(classB.cast(value)) + } + + companion object { + inline fun left(a: A): Either = + Either(a, A::class, B::class) + inline fun right(b: B): Either = + Either(b, A::class, B::class) + } +}