### tryRunningReduceIndexed Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Like `tryRunningReduce`, but the fallible operation also receives the index. The index starts at 1 (element at index 0 is the initial accumulator). ```APIDOC ## tryRunningReduceIndexed ### Description Like `tryRunningReduce`, but the fallible operation also receives the index. The index starts at 1 (element at index 0 is the initial accumulator). ### Method `inline fun Iterable.tryRunningReduceIndexed(operation: (index: Int, acc: S, T) -> Result): Result, E>` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result, E>** - A Result containing a list of all intermediate accumulation values (including index), or an error E if the operation failed. Returns an empty list if the input iterable was empty. #### Response Example N/A ``` -------------------------------- ### Kotlin Result Example Source: https://github.com/michaelbull/kotlin-result/wiki/Overhead Demonstrates the usage of the Result type with map, mapError, and andThen operations. This example showcases chaining operations on a Result. ```kotlin sealed interface Error object ErrorOne : Error object ErrorTwo : Error fun one(): Result { return Ok(50) } fun two(): Int { return 100 } fun three(int: Int): Result { return Ok(int + 25) } fun example() { val result = one() .map { two() } .mapError { ErrorTwo } .andThen(::three) .toString() println(result) } ``` -------------------------------- ### Create Email Address Parser Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Example of creating a Result type to indicate success or failure when parsing an email address. Handles cases like blank input, excessive length, and invalid format. ```kotlin object EmailAddressParser { fun parse(address: String?): Result { return when { address.isNullOrBlank() -> Err(EmailRequired) address.length > MAX_LENGTH -> Err(EmailTooLong) !address.matches(PATTERN) -> Err(EmailInvalid) else -> Ok(EmailAddress(address)) } } } ``` -------------------------------- ### Get Ok Value or Default with Either.fromLeft Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Retrieves the value from an Ok Result, or returns a specified default value if the Result is an Err. Useful for providing fallback values. ```kotlin val value: String = Err("error").getOr("default") // value = "default" ``` -------------------------------- ### tryRunningReduce Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Returns successive accumulation values generated by a fallible operation, starting with the first element. Returns Ok with an empty list if the iterable is empty. ```APIDOC ## tryRunningReduce ### Description Returns successive accumulation values generated by a fallible operation, starting with the first element. Returns Ok with an empty list if the iterable is empty. ### Method `inline fun Iterable.tryRunningReduce(operation: (acc: S, T) -> Result): Result, E>` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result, E>** - A Result containing a list of all intermediate accumulation values, or an error E if the operation failed. Returns an empty list if the input iterable was empty. #### Response Example N/A ``` -------------------------------- ### Decompiled Java Bytecode for Kotlin Result Source: https://github.com/michaelbull/kotlin-result/wiki/Overhead Shows the decompiled Java bytecode corresponding to the Kotlin Result example. Highlights zero object allocations for Ok paths and one for Err paths. ```java public final class Example { @NotNull public static final Example INSTANCE = new Example(); private Example() { } @NotNull public final Object one() { return this.Ok(50); } public final int two() { return 100; } @NotNull public final Object three(int var1) { return this.Ok(var1 + 25); } public final void example() { Object $this$map_u2dj2AeeQ8$iv = this.one(); Object var10000; if (Result.isOk_impl($this$map_u2dj2AeeQ8$iv)) { var10000 = this.Ok(INSTANCE.two()); } else { var10000 = $this$map_u2dj2AeeQ8$iv; } Object $this$mapError_u2dj2AeeQ8$iv = var10000; if (Result.isErr_impl($this$mapError_u2dj2AeeQ8$iv)) { var10000 = this.Err(ErrorTwo.INSTANCE); // object allocation (1) } else { var10000 = $this$mapError_u2dj2AeeQ8$iv; } Object $this$andThen_u2dj2AeeQ8$iv = var10000; if (Result.isOk_impl($this$andThen_u2dj2AeeQ8$iv)) { int p0 = ((Number) Result.getValue_impl($this$andThen_u2dj2AeeQ8$iv)).intValue(); var10000 = this.three(p0); } else { var10000 = $this$andThen_u2dj2AeeQ8$iv; } String result = Result.toString_impl(var10000); System.out.println(result); } @NotNull public final Object Ok(V value) { return Result.constructor_impl(value); } @NotNull public final Object Err(E error) { return Result.constructor_impl(new Failure(error)); } public static final class Result { @Nullable private final Object inlineValue; public static final V getValue_impl(Object arg0) { return arg0; } public static final E getError_impl(Object arg0) { Intrinsics.checkNotNull(arg0, "null cannot be cast to non-null type Failure"); return ((Failure) arg0).getError(); } public static final boolean isOk_impl(Object arg0) { return !(arg0 instanceof Failure); } public static final boolean isErr_impl(Object arg0) { return arg0 instanceof Failure; } @NotNull public static String toString_impl(Object arg0) { return isOk_impl(arg0) ? "Ok(" + getValue_impl(arg0) + ')' : "Err(" + getError_impl(arg0) + ')'; } @NotNull public String toString() { return toString_impl(this.inlineValue); } public static int hashCode_impl(Object arg0) { return arg0 == null ? 0 : arg0.hashCode(); } public int hashCode() { return hashCode_impl(this.inlineValue); } public static boolean equals_impl(Object arg0, Object other) { if (!(other instanceof Result)) { return false; } else { return Intrinsics.areEqual(arg0, ((Result) other).unbox_impl()); } } public boolean equals(Object other) { return equals_impl(this.inlineValue, other); } private Result(Object inlineValue) { this.inlineValue = inlineValue; } @NotNull public static Object constructor_impl(@Nullable Object inlineValue) { return inlineValue; } public static final Result box_impl(Object v) { ``` -------------------------------- ### Rust Result or_else Example Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Calls a transformation function if the Result is Err, otherwise returns the Ok value. Useful for control flow based on error values. ```kotlin fun sq(x: Int) = Ok(x * x) fun err(x: Int) = Err(x) val result = Ok(2).orElse(::sq).orElse(::sq) // result = Ok(2) val result = Ok(2).orElse(::err).orElse(::sq) // result = Ok(2) val result = Err(3).orElse(::sq).orElse(::err) // result = Ok(9) val result = Err(3).orElse(::err).orElse(::err) // result = Err(3) ``` -------------------------------- ### tryRunningFold Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Returns successive accumulation values generated by a fallible operation, starting with an initial value. Returns early with the first Err encountered. ```APIDOC ## tryRunningFold ### Description Returns successive accumulation values generated by a fallible operation, starting with an initial value. Returns early with the first Err encountered. ### Method `inline fun Iterable.tryRunningFold(initial: R, operation: (acc: R, T) -> Result): Result, E>` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result, E>** - A Result containing a list of all intermediate accumulation values, or an error E if the operation failed. #### Response Example N/A ``` -------------------------------- ### Rust Result transpose Example Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Transposes a Result of a nullable value into a nullable Result. Ok(null) becomes null, Ok(value) becomes Ok(value), and Err(error) becomes Err(error). ```kotlin val result = Ok(5).transpose() // result = Ok(5) val result = Ok(null).transpose() // result = null val result = Err("error").transpose() // result = Err("error") ``` -------------------------------- ### Get Value or Default (Scala Either.getOrElse) Source: https://github.com/michaelbull/kotlin-result/wiki/Scala The `getOr` function returns the `Ok` value if present, otherwise it returns the provided default value. This mirrors Scala's `Either.getOrElse`. ```kotlin Ok(12).getOr(17) // 12 Err(12).getOr(17) // 17 ``` -------------------------------- ### Convert Result to Option (Scala Either.toOption) Source: https://github.com/michaelbull/kotlin-result/wiki/Scala The `get` function attempts to retrieve the `Ok` value, returning `null` if the Result is an `Err`. This is similar to Scala's `Either.toOption`. ```kotlin Result.get(): V? ``` -------------------------------- ### Get Value or Fallback in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Extracts the Ok value from a result, or evaluates a function for a fallback value. Ideal for providing default values when an operation fails. ```kotlin val value = Ok(10).getOrElse { 0 } // value = 10 val value = Err("error").getOrElse { 0 } // value = 0 ``` -------------------------------- ### Rust Result flatten Example Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Converts from Result, E> to Result, removing one level of nesting. Flattening only removes one level of nesting at a time. ```kotlin val result = Ok(Ok("hello")).flatten() // result = Ok("hello") val result = Ok(Err(6)).flatten() // result = Err(6) val result = Err(6).flatten() // result = Err(6) val result = Ok(Ok(Ok("hello"))).flatten() // result = Ok(Ok("hello")) val result = Ok(Ok(Ok("hello"))).flatten().flatten() // result = Ok("hello") ``` -------------------------------- ### tryReduceIndexed Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Reduces elements from left to right using a fallible operation, also providing the index. The index starts at 1 for the first element used as the initial accumulator. ```APIDOC ## tryReduceIndexed ### Description Reduces elements from left to right using a fallible operation, also providing the index. The index starts at 1 for the first element used as the initial accumulator. ### Method `inline fun Iterable.tryReduceIndexed(operation: (index: Int, acc: T, T) -> Result): Result?` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result?** - The reduced value wrapped in a Result, or null if the iterable was empty. An error E is returned if the operation failed. #### Response Example N/A ``` -------------------------------- ### Running Reduce with Fallible Operation Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Generates successive accumulation values from an Iterable using a fallible operation, starting with the first element. Returns Ok with an empty list if the iterable is empty. Use to track intermediate results of a sequential computation. ```kotlin inline fun Iterable.tryRunningReduce(operation: (acc: S, T) -> Result): Result, E> ``` ```kotlin inline fun Iterable.tryRunningReduceIndexed(operation: (index: Int, acc: S, T) -> Result): Result, E> ``` -------------------------------- ### Constructing Kotlin Results Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Demonstrates various ways to create Result objects: directly with Ok/Err, from nullable values using `toResultOr`, and from exception-throwing code using `runCatching` or `runSuspendCatching`. ```kotlin val ok: Result = Ok(42) val err: Result = Err("something went wrong") val result: Result = nullableValue.toResultOr { MyError.NotFound } val result: Result = runCatching { riskyOperation() } val result: Result = runSuspendCatching { suspendingOperation() } ``` -------------------------------- ### tryScan Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Alias for `tryRunningFold`. Returns successive accumulation values generated by a fallible operation, starting with an initial value. ```APIDOC ## tryScan ### Description Alias for `tryRunningFold`. Returns successive accumulation values generated by a fallible operation, starting with an initial value. ### Method `inline fun Iterable.tryScan(initial: R, operation: (acc: R, T) -> Result): Result, E>` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result, E>** - A Result containing a list of all intermediate accumulation values, or an error E if the operation failed. #### Response Example N/A ``` -------------------------------- ### Get Iterator for Result Value Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Returns an iterator that yields the contained value if the Result is Ok. Otherwise, it throws NoSuchElementException. ```kotlin val iterator = Ok("hello").iterator() // iterator.hasNext() = true // iterator.next() = "hello" ``` -------------------------------- ### Factory Functions for Result Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Provides documentation for the factory functions used to create Result instances. ```APIDOC ## Factory Functions ### `fun Ok(value: V): Result` **Description**: Returns a Result that is Ok and contains the given value. ### `fun Err(error: E): Result` **Description**: Returns a Result that is Err and contains the given error. ### `inline fun runCatching(block: () -> V): Result` **Description**: Calls the block and returns its result, catching any Throwable as an Err. ### `inline infix fun T.runCatching(block: T.() -> V): Result` **Description**: Calls the block with `this` as its receiver, catching any Throwable as an Err. ### `inline infix fun V?.toResultOr(error: () -> E): Result` **Description**: Converts a nullable value to a Result. Returns Ok if non-null, otherwise Err with the supplied error. ``` -------------------------------- ### Convert a Result to a nullable type in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Elm The `get` function extracts the value from an `Ok` Result. If the Result is an `Err`, it returns `null`. ```kotlin val value = Ok(230).get() val error = Err("example").get() // value = 230 // error = null ``` -------------------------------- ### Or Combine Results in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Returns the first value if it is Ok, otherwise returns the second value. Useful for providing alternative results. ```kotlin val result = Ok(1).or(Ok(2)) // result = Ok(1) val result = Ok(1).or(Err("error")) // result = Ok(1) val result = Err("error").or(Ok(2)) // result = Ok(2) ``` -------------------------------- ### Add kotlin-result to Gradle libs.versions.toml Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Define the version and library coordinates for kotlin-result in your Gradle version catalog. ```kotlin // gradle/libs.versions.toml [versions] kotlin-result = "2.3.1" [libraries] kotlin-result = { module = "com.michael-bull.kotlin-result:kotlin-result", version.ref = "kotlin-result" } kotlin-result-coroutines = { module = "com.michael-bull.kotlin-result:kotlin-result-coroutines", version.ref = "kotlin-result" } ``` -------------------------------- ### Using Binding DSL for Sequential Operations Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt The `binding` DSL allows for sequential operations on Results, automatically handling errors and short-circuiting. ```kotlin val result: Result = binding { val a = getResultA().bind() val b = getResultB(a).bind() // ... b } ``` -------------------------------- ### Sequential Composition with Binding DSL Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt The `binding` DSL allows sequential composition of Result operations. Use `.bind()` within the block to unwrap Ok values or short-circuit on the first Err. ```kotlin sealed interface FormError { data object NameRequired : FormError data object EmailInvalid : FormError } fun validateName(name: String): Result { ... } fun validateEmail(email: String): Result { ... } val result: Result = binding { val name = validateName(input.name).bind() val email = validateEmail(input.email).bind() User(name, email) } ``` -------------------------------- ### Instantiate Result with Ok and Err Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Instantiate `Result` types using the top-level `Ok` and `Err` functions for brevity, contrasting with the more verbose `Result.success` and `Result.failure` companion object functions. ```kotlin val successResult: Result = Ok(10) val failureResult: Result = Err("Something went wrong") ``` -------------------------------- ### result.or Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Returns the first value if it is Ok, otherwise returns the second value. ```APIDOC ## result.or ### Description Returns the first value if it is `Ok`, otherwise returns the second value. ### Method ```kotlin Result.or(result: Result): Result ``` ### Request Example ```kotlin val result = Ok(1).or(Ok(2)) // result = Ok(1) val result = Ok(1).or(Err("error")) // result = Ok(1) val result = Err("error").or(Ok(2)) // result = Ok(2) ``` ``` -------------------------------- ### Combine five Results with a transformation in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Elm The `zip` function applies a transformation if all five provided `Result` producers return `Ok`. If any producer returns an `Err`, the first encountered error is propagated. ```kotlin val result = zip( { Ok(10) }, { Ok(20) }, { Ok(30) }, { Ok(40) }, { Ok(50) }, ) { a, b, c, d, e -> a + b + c + d + e } // result = Ok(150) ``` -------------------------------- ### Get Mutable Iterator for Result Value Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Returns a mutable iterator that yields the contained value if the Result is Ok. Allows removal of the element. Throws NoSuchElementException if the Result is Err. ```kotlin val iterator = Ok("hello").mutableIterator() iterator.remove() // iterator.hasNext() = false // iterator.next() throws NoSuchElementException ``` -------------------------------- ### Zip with Fail-Fast Behavior Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Use zip to combine multiple Result producers. It returns the first Err encountered, stopping further computation. Supports 2 to 5 arity. ```kotlin val result: Result = zip( { getName() }, { getAge() }, ) { name, age -> "$name is $age years old" } ``` -------------------------------- ### tryFind Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Returns the first element matching a fallible predicate, or null if no element matches. ```APIDOC ## tryFind ### Description Returns the first element matching a fallible predicate, or null if no element matches. ### Method `inline fun Iterable.tryFind(predicate: (T) -> Result): Result?` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result?** - The first element matching the predicate wrapped in a Result, or null if no element was found. An error E is returned if the predicate failed. #### Response Example N/A ``` -------------------------------- ### Get Err Value or Default with Either.fromRight Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Retrieves the error from an Err Result, or returns a specified default error value if the Result is an Ok. Useful for providing fallback error information. ```kotlin val error: String = Ok("hello").getErrorOr("world") // error = "world" ``` -------------------------------- ### Partition Results in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Partitions a list of results into a Pair of two lists — Ok values and Err values. Separates successful and failed outcomes. ```kotlin val pairs = partition( Ok("one"), Err("two"), Ok("three"), Err("four") ) // pairs.first = [ "one", "three" ] // pairs.second = [ "two", "four" ] ``` -------------------------------- ### Safe Unwrapping with getOrElse Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Prefer `getOrElse` for safe unwrapping of Result values in production code to handle potential errors gracefully. ```kotlin val result: Result = // ... val value = result.getOrElse { "Default Value" } ``` -------------------------------- ### Flow tryFold Operation Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Applies a suspend accumulating operation to each element of a Flow, starting with an initial value. The operation returns a Result. Returns the first Err encountered or a Result of the final accumulated value. ```kotlin suspend inline fun Flow.tryFold(initial: R, crossinline operation: suspend (acc: R, T) -> Result): Result ``` -------------------------------- ### Result.or Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Returns the second result if the first is Err, otherwise returns the Ok value of the first. ```APIDOC ## Result.or ### Description Returns `result` if this `Result` is `Err`, otherwise returns the `Ok` value of `this`. ### Method Signature ` Result.or(result: Result): Result` ### Example ```kotlin val result = Ok(2).or(Err("late error")) // result = Ok(2) val result = Err("early error").or(Ok(2)) // result = Ok(2) val result = Err("not a 2").or(Err("late error")) // result = Err("late error") val result = Ok(2).or(Ok(100)) // result = Ok(2) ``` ``` -------------------------------- ### Partition a List of Results in Kotlin Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Use the `partition` extension function on `Iterable>` to split a list of Results into a pair of lists: one containing successful values and the other containing errors. ```kotlin val (validAddresses, errors) = addresses .map(EmailAddressParser::parse) .partition() ``` -------------------------------- ### Result.map_or Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Applies a function to the Ok value or returns a default value if Err. ```APIDOC ## Result.map_or ### Description Applies a function to the contained value (if `Ok`), or returns the provided `default` (if `Err`). Arguments passed to `mapOr` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `mapOrElse`, which is lazily evaluated. ### Method ` Result.mapOr(default: U, transform: (V) -> U): U` ### Example ```kotlin val result = Ok("foo").mapOr(42, String::length) // result = 3 val result = Err("foo").mapOr(42, String::length) // result = 42 ``` ``` -------------------------------- ### Combine three Results with a transformation in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Elm The `zip` function applies a transformation if all three provided `Result` producers return `Ok`. If any producer returns an `Err`, the first encountered error is propagated. ```kotlin val result = zip( { Ok(10) }, { Ok(20) }, { Ok(30) }, ) { a, b, c -> a + b + c } // result = Ok(60) ``` -------------------------------- ### Handle Side Effects with onOk and onErr Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Use `onOk` to perform an action when the Result is Ok, and `onErr` for when it is Err. Both return the original Result. ```kotlin fetchUser(id) .onOk { logger.info("Fetched user: ${it.name}") } .onErr { logger.warn("Failed to fetch user: $it") } ``` -------------------------------- ### Perform Action on Each Element with Early Exit on Error Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Use `tryForEach` to apply an action to each element of an iterable. The operation stops and returns the first Err encountered. If all actions succeed, it returns Ok(Unit). ```kotlin val result = listOf(1, 2, 3).tryForEach { Ok(println(it)) } // result = Ok(Unit) val result = listOf(1, 2, 3).tryForEach { if (it > 2) Err("too big") else Ok(Unit) } // result = Err("too big") ``` -------------------------------- ### Combine four Results with a transformation in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Elm The `zip` function applies a transformation if all four provided `Result` producers return `Ok`. If any producer returns an `Err`, the first encountered error is propagated. ```kotlin val result = zip( { Ok(10) }, { Ok(20) }, { Ok(30) }, { Ok(40) }, ) { a, b, c, d -> a + b + c + d } // result = Ok(100) ``` -------------------------------- ### Either.either (mapBoth) Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell If the value is Ok(V), apply the first function to V; if it is Err(E), apply the second function to E. This is equivalent to Haskell's `either` function. ```APIDOC ## Either.either (mapBoth) ### Description If the value is `Ok(V)`, apply the first function to `V`; if it is `Err(E)`, apply the second function to `E`. ### Method Extension function on `Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val value: String = Ok("he").mapBoth( success = { "$it succeeded" }, failure = { "$it failed" } ) // value = "he succeeded" ``` ### Response #### Success Response (200) Returns the result of applying either the success or failure function. #### Response Example ```kotlin // For Ok("he") input: "he succeeded" // For Err("error") input: "error failed" ``` ``` -------------------------------- ### Result.unwrap_or Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Unwraps a Result, yielding the content of an Ok. If the Result is an Err, it returns a provided default value. ```APIDOC ## Result.unwrap_or ### Description Unwraps a `Result`, yielding the content of an `Ok`. Else, it returns `default`. Arguments passed to `getOr` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `getOrElse`, which is lazily evaluated. ### Method Signature ` Result.getOr(default: V): V` ### Example Usage ```kotlin val value = Err("error").getOr("default") // value = default ``` ``` -------------------------------- ### Partitioning Iterable> Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Enables partitioning an Iterable of Results into two separate collections: one for Ok values and one for Err errors, with options for destination collections and vararg convenience functions. ```APIDOC ## Partitioning Iterable> ### Description Functions to partition an `Iterable>` into separate collections of `Ok` values and `Err` errors. ### Methods - `fun Iterable>.partition(): Pair, List>` - Splits the `Iterable` into a `Pair` containing a `List` of `Ok` values and a `List` of `Err` errors. - `fun , CE : MutableCollection> Iterable>.partitionTo(first: CV, second: CE): Pair` - Partitions the `Iterable` into the provided `first` (for Ok values) and `second` (for Err errors) destination collections. ### Vararg Convenience Function - `fun > partition(vararg results: R): Pair, List>` ``` -------------------------------- ### Extract Ok Value or Default Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Use `getOr` to safely extract the success value from a Result. If the Result is an Err, a provided default value is returned instead. ```kotlin val value = Ok(10).getOr(0) // value = 10 val value = Err("error").getOr(0) // value = 0 ``` -------------------------------- ### result.replace Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Replaces the Ok value with a new value, leaving Err unchanged. ```APIDOC ## result.replace ### Description Replaces the `Ok` value with a new value, leaving `Err` unchanged. ### Method ```kotlin Result.map(transform: (V) -> U): Result ``` ### Request Example ```kotlin val result = Ok(1).map { 2 } // result = Ok(2) val result = Err("error").map { 2 } // result = Err("error") ``` ``` -------------------------------- ### Extract Ok Values with Either.lefts Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Collects all successful (Ok) values from a variable number of Result instances into a list. Preserves the order of the Ok values. ```kotlin val values: List = valuesOf( Ok("hello"), Ok("world") ) // values = [ "hello", "world" ] ``` -------------------------------- ### Result.and Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Returns the second result if the first is Ok, otherwise returns the Err value of the first. ```APIDOC ## Result.and ### Description Returns `result` if this `Result` is `Ok`, otherwise returns the `Err` value of `this`. ### Method Signature ` Result.and(result: Result): Result` ### Example ```kotlin val result = Ok(2).and(Err("late error")) // result = Err("late error") val result = Err("early error").and(Ok("foo")) // result = Err("early error") val result = Err("not a 2").and(Err("late error")) // result = Err("not a 2") val result = Ok(2).and(Ok("different result type")) // result = Ok("different result type") ``` ``` -------------------------------- ### Either.fromLeft (getOr) Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Return the value of an Ok-result or a default value otherwise. This is equivalent to Haskell's `fromLeft` when used with a default. ```APIDOC ## Either.fromLeft (getOr) ### Description Return the value of an `Ok`-result or a default value otherwise. ### Method Extension function on `Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val value: String = Err("error").getOr("default") // value = "default" ``` ### Response #### Success Response (200) The `Ok` value if present, otherwise the provided default value. #### Response Example ```kotlin "default" ``` ``` -------------------------------- ### Combine two Results with a transformation in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Elm The `zip` function applies a transformation if both provided `Result` producers return `Ok`. If either producer returns an `Err`, the first encountered error is propagated. ```kotlin val result = zip( { Ok(10) }, { Ok(20) }, ) { a, b -> a + b } // result = Ok(30) ``` -------------------------------- ### Add kotlin-result Dependency Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Add this dependency to your project's build file to use the kotlin-result library. ```groovy repositories { mavenCentral() } dependencies { implementation("com.michael-bull.kotlin-result:kotlin-result:2.3.1") } ``` -------------------------------- ### Combine Results with 'or' Source: https://github.com/michaelbull/kotlin-result/wiki/Rust Returns the second Result if the first is Err, otherwise returns the first Result's Ok. Useful for providing default values or alternative computations. ```kotlin val result = Ok(2).or(Err("late error")) // result = Ok(2) ``` ```kotlin val result = Err("early error").or(Ok(2)) // result = Ok(2) ``` ```kotlin val result = Err("not a 2").or(Err("late error")) // result = Err("late error") ``` ```kotlin val result = Ok(2).or(Ok(100)) // result = Ok(2) ``` -------------------------------- ### tryForEach Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Performs a fallible action on each element of an Iterable. The action returns a Result. ```APIDOC ## tryForEach ### Description Performs a fallible action on each element of an Iterable. The action returns a Result. ### Method `inline fun Iterable.tryForEach(action: (V) -> Result<*, E>): Result` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result** - A Result indicating Unit on success, or an error E if the action failed on any element. #### Response Example N/A ``` -------------------------------- ### Sequential Binding for Dependent Operations Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Use `binding` for a sequence of operations where each step depends on the successful result of the previous one. This simplifies chaining fallible operations. ```kotlin fun placeOrder(userId: Long, itemId: Long): Result = binding { val user = findUser(userId).bind() val item = findItem(itemId).bind() val stock = checkStock(item).bind() val order = createOrder(user, item, stock).bind() order } ``` -------------------------------- ### Partition Results into Ok and Err Lists Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Separates an iterable of Results into two lists: one for Ok values and one for Err values. Maintains the original order within each list. ```kotlin val pairs: Pair, List> = partition( Err("c#"), Ok("haskell"), Err("java"), Ok("f#"), Err("c"), Ok("elm"), Err("lua"), Ok("clojure"), Err("javascript") ) // pairs.first = [ "haskell", "f#", "elm", "clojure" ] // pairs.second = [ "c#", "java", "c", "lua", "javascript"] ``` -------------------------------- ### list.try_each Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Applies an action to each element of a list sequentially. If the action returns an Err at any point, the iteration stops and that Err is returned. Otherwise, a Unit Ok is returned. ```APIDOC ## list.try_each ### Description Calls a function for each element, returning early with the first `Err`. ### Method Signature ` Iterable.tryForEach(action: (V) -> Result<*, E>): Result` ### Example ```kotlin val result = listOf(1, 2, 3).tryForEach { Ok(println(it)) } // result = Ok(Unit) val result = listOf(1, 2, 3).tryForEach { if (it > 2) Err("too big") else Ok(Unit) } // result = Err("too big") ``` ``` -------------------------------- ### result.partition Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Partitions a list of results into a Pair of two lists — Ok values and Err values. ```APIDOC ## result.partition ### Description Partitions a list of results into a `Pair` of two lists — `Ok` values and `Err` values. ### Method ```kotlin Iterable>.partition(): Pair, List> ``` ### Request Example ```kotlin val pairs = partition( Ok("one"), Err("two"), Ok("three"), Err("four") ) // pairs.first = [ "one", "three" ] // pairs.second = [ "two", "four" ] ``` ``` -------------------------------- ### Bifunctor.first (map) Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Map covariantly over the first argument (the Ok value). This is equivalent to Haskell's `fmap` or `map` for Functors. ```APIDOC ## Bifunctor.first (map) ### Description Map covariantly over the first argument (the `Ok` value). ### Method Extension function on `Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val result = Ok(10).map { it + 20 } // result = Ok(30) ``` ### Response #### Success Response (200) A new `Result` with the `Ok` value transformed. #### Response Example ```kotlin Ok(30) ``` ``` -------------------------------- ### result.try Source: https://github.com/michaelbull/kotlin-result/wiki/Gleam Chains together computations that may fail. If the Result is Ok, the provided transformation function is applied. If it's an Err, the error is propagated. ```APIDOC ## result.try ### Description Chains together computations that may fail. If the result is `Ok`, the function is applied. If the result is an `Err`, it is returned unchanged. Also available as `flatMap`. ### Method Signature ` Result.andThen(transform: (V) -> Result): Result` ### Example ```kotlin val result = Ok(1).andThen { Ok(it * 2) }.andThen { Ok(it + 10) } // result = Ok(12) val result = Ok(1).andThen { Err("failed") }.andThen { Ok(it + 10) } // result = Err("failed") ``` ``` -------------------------------- ### tryRunningFoldIndexed Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Similar to `tryRunningFold`, but the fallible operation also receives the index of the current element. ```APIDOC ## tryRunningFoldIndexed ### Description Similar to `tryRunningFold`, but the fallible operation also receives the index of the current element. ### Method `inline fun Iterable.tryRunningFoldIndexed(initial: R, operation: (index: Int, acc: R, T) -> Result): Result, E>` ### Endpoint N/A (Extension function on Iterable) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response - **Result, E>** - A Result containing a list of all intermediate accumulation values (including index), or an error E if the operation failed. #### Response Example N/A ``` -------------------------------- ### Combine independent Results with zip in Kotlin Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Use `zip` to combine multiple independent Result computations. It returns early with the first error encountered. Supports 2-5 arity. ```kotlin fun validate(dto: CustomerDto): Result { return zip( { PersonalNameParser.parse(dto.firstName, dto.lastName) }, { EmailAddressParser.parse(dto.email) }, ::Customer ) } ``` -------------------------------- ### Add kotlin-result to build.gradle.kts Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Include the core kotlin-result library in your project's build script. Add the coroutines module if you need its extensions. ```kotlin // build.gradle.kts dependencies { implementation(libs.kotlin.result) // Optional: only if you need coroutineBinding, runSuspendCatching, parZip, or Flow extensions implementation(libs.kotlin.result.coroutines) } ``` -------------------------------- ### Parallel Zipping of Coroutines with parZip Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Apply a transform to multiple Results in parallel using parZip. It returns early with the first Err encountered and uses coroutineBinding internally. Available for 2 to 5 producers. ```kotlin val result = parZip( { fetchUser(userId) }, { fetchOrders(userId) }, ) { user, orders -> UserProfile(user, orders) } ``` -------------------------------- ### Handling Specific Exceptions Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Instead of catching generic `Throwable`, catch specific exceptions to avoid masking unrelated bugs and to preserve failure identity. ```kotlin runCatching { // ... potentially risky operation ... }.onFailure { when (it) { is SpecificException -> // handle specific error else -> throw it // rethrow unexpected errors } } ``` -------------------------------- ### Chain Operations with andThen Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Use `andThen` to chain operations where each step can potentially fail. The success value of one operation is passed to the next, allowing for sequential processing of fallible steps. ```kotlin val (status, body) = call.parameters .readId() .andThen(::parseCustomerId) .andThen(::findById) .map(::entityToDto) .mapBoth(::customerToResponse, ::messageToResponse) ``` -------------------------------- ### Result.withDefault Source: https://github.com/michaelbull/kotlin-result/wiki/Elm Retrieves the value from an Ok Result, or returns a specified default value if the Result is an Err. ```APIDOC ## Result.withDefault ### Description If the result is `Ok` return the value, but if the result is an `Err` then return a given default value. ### Method Signature ` Result.getOr(default: V): V` ### Request Example ```kotlin val value = Err("error").getOr("default") // value = default ``` ``` -------------------------------- ### Pipeline Transformations with andThen Source: https://github.com/michaelbull/kotlin-result/blob/master/llms-full.txt Employ `andThen` for a series of transformations in a pipeline, where each stage can potentially fail. This is suitable for sequential processing of data that might encounter errors. ```kotlin fun processPayment(orderId: Long): Result { return findOrder(orderId) .andThen(::validateOrder) .andThen(::chargePayment) .andThen(::generateReceipt) } ``` -------------------------------- ### Success Class Implementation in Kotlin Source: https://github.com/michaelbull/kotlin-result/wiki/Overhead Internal implementation of the Success state for the Result class. It holds an inline value and provides equality and hashing based on that value. ```kotlin static final class Success { private final T inlineValue; public Success(T inlineValue) { this.inlineValue = inlineValue; } public final T getInlineValue() { return this.inlineValue; } public boolean equals(@Nullable Object other) { return other instanceof Success && Intrinsics.areEqual(this.inlineValue, ((Success)other).inlineValue); } public int hashCode() { Object var10000 = this.inlineValue; return var10000 != null ? var10000.hashCode() : 0; } @NotNull public String toString() { return "Success(" + this.inlineValue + ')'; } public final Object unbox_impl() { return this.inlineValue; } public static final boolean equals_impl0(Object p1, Object p2) { return Intrinsics.areEqual(p1, p2); } } ``` -------------------------------- ### Capture Exceptions with runCatching Source: https://github.com/michaelbull/kotlin-result/blob/master/README.md Wrap calls that may throw exceptions using `runCatching` to capture the execution as a `Result`. This is useful for handling potential errors gracefully. ```kotlin val result: Result = runCatching { repository.save(customer) } ``` -------------------------------- ### Bifunctor.bimap Source: https://github.com/michaelbull/kotlin-result/wiki/Haskell Map over both arguments at the same time. This allows transforming both the Ok and Err values of a Result. ```APIDOC ## Bifunctor.bimap ### Description Map over both arguments at the same time. ### Method Extension function on `Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val result: Result = Err("the reckless").bimap( success = { "the wild youth" }, failure = { "the truth" } ) // result = Err("the truth") ``` ### Response #### Success Response (200) A new `Result` with transformed `Ok` and `Err` values. #### Response Example ```kotlin // For Ok("value") input with success transform: Ok("transformed_value") // For Err("error") input with failure transform: Err("transformed_error") ``` ``` -------------------------------- ### Bind Function Across Ok (Scala Either.flatMap) Source: https://github.com/michaelbull/kotlin-result/wiki/Scala The `flatMap` function applies a transform to the `Ok` value, allowing for chained operations. If the Result is an `Err`, it is passed through unchanged. ```kotlin val result = Ok(12).flatMap { Ok("flower") } // result = Ok("flower") val result = Err(12).flatMap { Ok("flower") } // result = Err(12) ```