Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Unverified Commit 8b559295 authored by Sebastiano Barezzi's avatar Sebastiano Barezzi
Browse files

Twelve: Result: Add `onSuccess`/`onError` methods

Change-Id: I387a90568cf4302ce8d3856d8885aeb7d9ab87a2
parent 5131a690
Loading
Loading
Loading
Loading
+28 −0
Original line number Diff line number Diff line
@@ -51,5 +51,33 @@ sealed interface Result<T, E> {
        inline fun <T, E, R> Result<T, E>.map(
            mapping: (T) -> R
        ): Result<R, E> = flatMap { Success(mapping(it)) }

        /**
         * Execute a block if the result is [Success].
         *
         * @param block The block to execute
         */
        inline fun <R : Result<T, E>, reified T, E> R.onSuccess(
            block: (T) -> Unit,
        ): R = this.also {
            when (this) {
                is Success<*, *> -> block(data as T)
                is Error<*, *> -> Unit
            }
        }

        /**
         * Execute a block if the result is [Error].
         *
         * @param block The block to execute
         */
        inline fun <R : Result<T, E>, T, reified E> R.onError(
            block: (E) -> Unit,
        ): R = this.also {
            when (this) {
                is Success<*, *> -> Unit
                is Error<*, *> -> block(error as E)
            }
        }
    }
}