From 3c09056e22490df04c53ea73c09439c8c49f26c4 Mon Sep 17 00:00:00 2001 From: Andras Slemmer Date: Tue, 15 Nov 2016 18:05:00 +0000 Subject: [PATCH] Remove :Any restriction from ErrorOr's type parameter --- core/src/main/kotlin/net/corda/core/Utils.kt | 30 +++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/core/src/main/kotlin/net/corda/core/Utils.kt b/core/src/main/kotlin/net/corda/core/Utils.kt index 5599fef868..f8a47f810b 100644 --- a/core/src/main/kotlin/net/corda/core/Utils.kt +++ b/core/src/main/kotlin/net/corda/core/Utils.kt @@ -285,7 +285,8 @@ fun extractZipFile(zipPath: Path, toPath: Path) { val Throwable.rootCause: Throwable get() = Throwables.getRootCause(this) /** Representation of an operation that may have thrown an error. */ -data class ErrorOr private constructor(val value: A?, val error: Throwable?) { +data class ErrorOr private constructor(val value: A?, val error: Throwable?) { + // The ErrorOr holds a value iff error == null constructor(value: A) : this(value, null) companion object { @@ -295,31 +296,38 @@ data class ErrorOr private constructor(val value: A?, val error: Th } fun match(onValue: (A) -> T, onError: (Throwable) -> T): T { - if (value != null) { - return onValue(value) + if (error == null) { + return onValue(value as A) } else { - return onError(error!!) + return onError(error) } } fun getOrThrow(): A { - if (value != null) { - return value + if (error == null) { + return value as A } else { - throw error!! + throw error } } // Functor - fun map(function: (A) -> B) = ErrorOr(value?.let(function), error) + fun map(function: (A) -> B) = ErrorOr(value?.let(function), error) // Applicative - fun combine(other: ErrorOr, function: (A, B) -> C): ErrorOr { - return ErrorOr(value?.let { a -> other.value?.let { b -> function(a, b) } }, error ?: other.error) + fun combine(other: ErrorOr, function: (A, B) -> C): ErrorOr { + val newError = error ?: other.error + return ErrorOr(if (newError == null) null else function(value as A, other.value as B), newError) } // Monad - fun bind(function: (A) -> ErrorOr) = value?.let(function) ?: ErrorOr.of(error!!) + fun bind(function: (A) -> ErrorOr): ErrorOr { + return if (error == null) { + function(value as A) + } else { + ErrorOr.of(error) + } + } } /**