From f0fb536516e4799a76c7a02930555cdd14c70cd3 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Sun, 22 Oct 2017 15:08:23 +0100 Subject: [PATCH] Add Result.of factory method Inspired by result4k, invokes a callback within a try/catch block, returning an Error if an exception was thrown and Ok otherwise. --- .../com/github/michaelbull/result/Result.kt | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/com/github/michaelbull/result/Result.kt b/src/main/kotlin/com/github/michaelbull/result/Result.kt index f5bd24e..9f3b1f9 100644 --- a/src/main/kotlin/com/github/michaelbull/result/Result.kt +++ b/src/main/kotlin/com/github/michaelbull/result/Result.kt @@ -7,7 +7,22 @@ package com.github.michaelbull.result * - Haskell: [Data.Either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html) * - Rust: [Result](https://doc.rust-lang.org/std/result/enum.Result.html) */ -sealed class Result +sealed class Result { + companion object { + + /** + * Invokes a [function] and wraps it in a [Result], returning an [Error] if a [Throwable] + * was thrown, otherwise [Ok]. + */ + inline fun of(function: () -> T): Result { + return try { + Ok(function.invoke()) + } catch (t: Throwable) { + Error(t) + } + } + } +} data class Ok constructor(val value: V) : Result() data class Error constructor(val error: E) : Result()