Result type


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, which includes an interface Result similar to Rust Result, and includes an interface Either similar to Haskell Either a b. Because Java and Kotlin are cross-compatible, Java can use the Result 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 and .
  • 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 !T as the return type of a function. For example fn my_function !string . .

C++

The expected class uses std::unexpected to return the type E, and can return T directly.

import std;
using std::expected;
using std::ifstream;
using std::string;
using std::stringstream;
using std::unexpected;
using std::filesystem::path;
enum class FileError ;
expected loadConfig noexcept
int main

Rust

Enums in Rust are tagged unions, which can be unpacked with strong type checking through pattern matching.

const CAT_FOUND: bool = true;
fn main
fn pet_cat -> Result<, String>

Vlang

The Error type is an interface for iError.

const cat_found = true
fn main
fn get_pet_cat_name !string