Skip to content

Commit 8f3c8ac

Browse files
committed
Add Either type with left, right and match functions
1 parent deb5425 commit 8f3c8ac

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

  • app/src/main/java/org/schabi/newpipe/util
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package org.schabi.newpipe.util
2+
3+
import androidx.compose.runtime.Stable
4+
import kotlin.reflect.KClass
5+
import kotlin.reflect.cast
6+
import kotlin.reflect.safeCast
7+
8+
@Stable
9+
data class Either<A : Any, B : Any>(
10+
val value: Any,
11+
val classA: KClass<A>,
12+
val classB: KClass<B>,
13+
) {
14+
inline fun <R> match(ifLeft: (A) -> R, ifRight: (B) -> R): R {
15+
return classA.safeCast(value)?.let { ifLeft(it) }
16+
?: ifRight(classB.cast(value))
17+
}
18+
19+
companion object {
20+
inline fun <reified A : Any, reified B : Any> left(a: A): Either<A, B> =
21+
Either(a, A::class, B::class)
22+
inline fun <reified A : Any, reified B : Any> right(b: B): Either<A, B> =
23+
Either(b, A::class, B::class)
24+
}
25+
}

0 commit comments

Comments
 (0)