From HandWiki - Reading time: 4 min
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.
std::expected<T, E>.[1]type Result e v = Ok v | Err e.[2]Either type is used for this purpose, which is defined by the standard library as data Either a b = Left a | Right b, where a is the error type and b is the return type.[3]Result<R, E> similar to Rust Result<T, E>, and vavr includes an interface Either<L, R> similar to Haskell Either a b. Because Java and Kotlin are cross-compatible, Java can use the Result type from Kotlin.value class Result<out T>.[4]type ('a, 'b) result = Ok of 'a | Error of 'b type.[5]enum Result<T, E> { Ok(T), Err(E) }.[6][7]Either type,[8] however Scala also has more conventional exception handling.@frozen enum Result<Success, Failure> where Failure : Error.[9]!T as the return type of a function. For example fn my_function() !string { ... }. Error Handling in V.The expected<T, E> 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 {
MissingFile,
NoPermission,
// more errors here
};
expected<string, FileError> loadConfig(const path& p) noexcept {
if (!std::filesystem::exists(p)) {
return unexpected(FileError::MissingFile);
}
ifstream config{p};
stringstream buffer;
if (!config.is_open()) {
return unexpected(FileError::NoPermission);
}
buffer << config.rdbuf();
config.close();
return buffer.str();
}
int main(int argc, char* argv[]) {
path p{/* some path here */};
if (const expected<String, FileError> s = loadConfig(p); s.has_value()) {
std::println("Config contents: {}", s.value());
} else if (s.error() == FileError::MissingFile) {
std::println("Error: path {} not valid or missing!", p);
} else if (s.error() == FileError::NoPermission) {
std::println("Error: no permission to read file at path {}!", p);
} else {
std::unreachable();
}
}
The result object has the methods is_ok() and is_err().
const CAT_FOUND: bool = true;
fn main() {
let result: Result<(), String> = pet_cat();
if result.is_ok() {
println!("Great, we could pet the cat!");
} else {
let error: String = result.unwrap_err();
println!("Oh no, we couldn't pet the cat: {}", error);
}
}
fn pet_cat() -> Result<(), String> {
if CAT_FOUND {
Ok(())
} else {
Err(String::from("The cat is nowhere to be found!"))
}
}
The Error type is an interface for iError.
const cat_found = true
fn main() {
cat_name := get_pet_cat_name() or {
println("Oh no, we couldn't pet the cat!")
exit(1)
}
println('Great, we could pet the cat ' + cat_name)
}
fn get_pet_cat_name() !string {
if cat_found { return 'Max' }
else { return error('the cat is nowhere to be found') }
}