In functional programming, a result type is a monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption.
Examples
- In C++, it is defined by the standard library as .
- In Elm, it is defined by the standard library as .
- In Haskell, by convention the type is used for this purpose, which is defined by the standard library as , where is the error type and is the return type.
- In Java, it is not natively in the standard library, but is available from third party libraries. For example, result4j which includes an interface <code>Result<R, E></code> similar to Rust <code>Result<T, E></code>, and vavr includes an interface <code>Either<L, R></code> similar to Haskell <code>Either a b</code>. Because Java and Kotlin are cross-compatible, Java can use the <code>Result</code> type from Kotlin.
- In Kotlin, it is defined by the standard library as .
- In OCaml, it is defined by the standard library as .
- In Python, it is not natively in the standard library, but is available from third party libraries such as returns and result.
- In Rust, it is defined by the standard library as .
- In Scala, the standard library also defines an type, however Scala also has more conventional exception handling.
- In Swift, it is defined by the standard library as .
- In V, the result type is implemented natively using <code>!T</code> as the return type of a function. For example <code>fn my_function() !string { ... }</code>. Error Handling in V.
C++
The <code>expected<T, E></code> class uses <code>std::unexpected()</code> to return the type <code>E</code>, and can return <code>T</code> directly.
Rust
Enums in Rust are tagged unions, which can be unpacked with strong type checking through pattern matching.
Vlang
The <code>Error</code> type is an interface for <code>iError</code>.
See also
References