From e337cd98c8594eb92e3a5c434743b21fa3097ecc Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 17 Nov 2021 21:31:35 +0600 Subject: [PATCH] optional workaround --- CHANGELOG.md | 1 + .../dev/inmo/micro_utils/common/Optional.kt | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 410ddfff15d..19db51c1b84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * `Common`: * Ranges intersection functionality + * New type `Optional` * `Pagination`: * `Pagination` now extends `ClosedRange` * `Pagination` intersection functionality diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Optional.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Optional.kt index 82919cfc60c..a166434beb7 100644 --- a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Optional.kt +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Optional.kt @@ -50,3 +50,24 @@ fun Optional.onPresented(block: (T) -> Unit): Optional = apply { fun Optional.onAbsent(block: () -> Unit): Optional = apply { if (!dataPresented) { block() } } + +/** + * Returns [Optional.data] if [Optional.dataPresented] of [this] is true, or null otherwise + */ +fun Optional.dataOrNull() = if (dataPresented) data as T else null + +/** + * Returns [Optional.data] if [Optional.dataPresented] of [this] is true, or throw [throwable] otherwise + */ +fun Optional.dataOrThrow(throwable: Throwable) = if (dataPresented) data as T else throw throwable + + +/** + * Returns [Optional.data] if [Optional.dataPresented] of [this] is true, or call [block] and returns the result of it + */ +fun Optional.dataOrElse(block: () -> T) = if (dataPresented) data as T else block() + +/** + * Returns [Optional.data] if [Optional.dataPresented] of [this] is true, or call [block] and returns the result of it + */ +suspend fun Optional.dataOrElseSuspendable(block: suspend () -> T) = if (dataPresented) data as T else block()