diff --git a/CHANGELOG.md b/CHANGELOG.md index 85fc346b4e7..a088166fe30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 0.7.4 +* `Common`: + * New type `Either` + ## 0.7.3 * `Versions`: diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Either.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Either.kt new file mode 100644 index 00000000000..20625edbd41 --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Either.kt @@ -0,0 +1,45 @@ +package dev.inmo.micro_utils.common + +/** + * Realization of this interface will contains at least one not null - [t1] or [t2] + * + * @see EitherFirst + * @see EitherSecond + * @see Either.Companion.first + * @see Either.Companion.second + * @see Either.onFirst + * @see Either.onSecond + */ +sealed interface Either { + val t1: T1? + val t2: T2? + + companion object +} + +data class EitherFirst( + override val t1: T1 +) : Either { + override val t2: T2? + get() = null +} + +data class EitherSecond( + override val t2: T2 +) : Either { + override val t1: T1? + get() = null +} + +inline fun Either.Companion.first(t1: T1): Either = EitherFirst(t1) +inline fun Either.Companion.second(t1: T1): Either = EitherFirst(t1) + +inline fun > E.onFirst(crossinline block: (T1) -> Unit): E { + if (this is EitherFirst<*, *>) block(t1 as T1) + return this +} + +inline fun > E.onSecond(crossinline block: (T2) -> Unit): E { + if (this is EitherSecond<*, *>) block(t2 as T2) + return this +}