2021-10-28 12:02:02 +00:00
|
|
|
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<T1, T2> {
|
|
|
|
val t1: T1?
|
|
|
|
val t2: T2?
|
|
|
|
|
|
|
|
companion object
|
|
|
|
}
|
|
|
|
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* This type [Either] will always have not nullable [t1]
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
data class EitherFirst<T1, T2>(
|
|
|
|
override val t1: T1
|
|
|
|
) : Either<T1, T2> {
|
|
|
|
override val t2: T2?
|
|
|
|
get() = null
|
|
|
|
}
|
|
|
|
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* This type [Either] will always have not nullable [t2]
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
data class EitherSecond<T1, T2>(
|
|
|
|
override val t2: T2
|
|
|
|
) : Either<T1, T2> {
|
|
|
|
override val t1: T1?
|
|
|
|
get() = null
|
|
|
|
}
|
|
|
|
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* @return New instance of [EitherFirst]
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
inline fun <T1, T2> Either.Companion.first(t1: T1): Either<T1, T2> = EitherFirst(t1)
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* @return New instance of [EitherSecond]
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
inline fun <T1, T2> Either.Companion.second(t1: T1): Either<T1, T2> = EitherFirst(t1)
|
|
|
|
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* Will call [block] in case when [Either.t1] of [this] is not null
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
inline fun <T1, T2, E : Either<T1, T2>> E.onFirst(crossinline block: (T1) -> Unit): E {
|
2021-10-28 12:42:05 +00:00
|
|
|
val t1 = t1
|
|
|
|
t1 ?.let(block)
|
2021-10-28 12:02:02 +00:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2021-10-28 12:42:05 +00:00
|
|
|
/**
|
|
|
|
* Will call [block] in case when [Either.t2] of [this] is not null
|
|
|
|
*/
|
2021-10-28 12:02:02 +00:00
|
|
|
inline fun <T1, T2, E : Either<T1, T2>> E.onSecond(crossinline block: (T2) -> Unit): E {
|
2021-10-28 12:42:05 +00:00
|
|
|
val t2 = t2
|
|
|
|
t2 ?.let(block)
|
2021-10-28 12:02:02 +00:00
|
|
|
return this
|
|
|
|
}
|