From 83fe5d3ef1347d74c72d2c6a68e87df002311410 Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Tue, 19 Mar 2024 18:00:42 +0700 Subject: [PATCH] KOptional.orThrow --- gradle.properties | 2 +- .../kotlin/ru/dbotthepony/kommons/util/KOptional.kt | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 52907db..0e3fcfb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ kotlin.code.style=official specifyKotlinAsDependency=false projectGroup=ru.dbotthepony.kommons -projectVersion=2.9.21 +projectVersion=2.9.22 guavaDepVersion=33.0.0 gsonDepVersion=2.8.9 diff --git a/src/main/kotlin/ru/dbotthepony/kommons/util/KOptional.kt b/src/main/kotlin/ru/dbotthepony/kommons/util/KOptional.kt index 61a292d..8bc520a 100644 --- a/src/main/kotlin/ru/dbotthepony/kommons/util/KOptional.kt +++ b/src/main/kotlin/ru/dbotthepony/kommons/util/KOptional.kt @@ -26,6 +26,9 @@ class KOptional private constructor(private val _value: T, val isPresent: Boo throw NoSuchElementException("No value is present") } + inline val isEmpty: Boolean + get() = !isPresent + inline fun ifPresent(block: (T) -> Unit): KOptional { if (isPresent) { block.invoke(value) @@ -75,6 +78,14 @@ class KOptional private constructor(private val _value: T, val isPresent: Boo } } + inline fun orThrow(supplier: () -> Throwable): T { + if (isPresent) { + return this.value + } else { + throw supplier.invoke() + } + } + infix fun or(value: KOptional): KOptional { if (isPresent) { return this