From e276d706d6f4409c913c35646f88e99e495f1409 Mon Sep 17 00:00:00 2001 From: Stypox Date: Tue, 28 Jan 2025 11:12:06 +0100 Subject: [PATCH] Add Either type with left, right and match functions --- .../java/org/schabi/newpipe/util/Either.kt | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 app/src/main/java/org/schabi/newpipe/util/Either.kt 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) + } +}