diff --git a/README.md b/README.md index 81d09fc..a90389f 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,9 @@ Current extension functions: - [`varargsToList/glue`](https://github.com/robstoll/kbox/tree/main/src/commonMain/kotlin/ch/tutteli/kbox/varargToList.kt#L11) creates a `List` out of a single `E` and an `Array`. +- [takeIf](https://github.com/robstoll/kbox/tree/main/src/commonMain/kotlin/ch/tutteli/kbox/takeIf.kt#L12) + same behaviour as `takeIf` but as prefix operator and not postfix. + Moreover, the following function might come in handy for you as well: - [identity](https://github.com/robstoll/kbox/tree/main/src/commonMain/kotlin/ch/tutteli/kbox/identity.kt) diff --git a/src/commonMain/kotlin/ch/tutteli/kbox/takeIf.kt b/src/commonMain/kotlin/ch/tutteli/kbox/takeIf.kt new file mode 100644 index 0000000..8252cd6 --- /dev/null +++ b/src/commonMain/kotlin/ch/tutteli/kbox/takeIf.kt @@ -0,0 +1,12 @@ +package ch.tutteli.kbox + +/** + * Calls the [provider] only if the [predicate] holds, returns `null` otherwise. + * + * This function shall complement `takeIf` from the stdlib of Kotlin for cases where the cost to call the provider + * is high or the code involved to define the provider is long and a postfix `takeIf` is less readable + * than stating it at the beginning. + * + * @since 1.0.0 + */ +inline fun takeIf(predicate: Boolean, provider: () -> R): R? = if (predicate) provider() else null diff --git a/src/commonTest/kotlin/ch/tutteli/kbox/TakeIfSpec.kt b/src/commonTest/kotlin/ch/tutteli/kbox/TakeIfSpec.kt new file mode 100644 index 0000000..2423b5b --- /dev/null +++ b/src/commonTest/kotlin/ch/tutteli/kbox/TakeIfSpec.kt @@ -0,0 +1,21 @@ +package ch.tutteli.kbox + +import ch.tutteli.atrium.api.fluent.en_GB.toEqual +import ch.tutteli.kbox.atrium.expect +import org.spekframework.spek2.Spek +import org.spekframework.spek2.style.specification.describe + +object TakeIfSpec : Spek({ + + describe("fun ${::takeIf.name}}") { + it("it returns null if predicate doesn't hold") { + expect( + takeIf(false) { throw IllegalArgumentException("bla") } + ).toEqual(null) + } + + it("it returns null if predicate doesn't hold") { + expect(takeIf(true) { 1 }).toEqual(1) + } + } +})