Skip to content

Commit

Permalink
Merge pull request #201 from robstoll/feature/takeIf
Browse files Browse the repository at this point in the history
takeIf as prefix operation
  • Loading branch information
robstoll authored Mar 4, 2024
2 parents f7e186f + e94d14c commit feb4f70
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<E>`.

- [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)

Expand Down
12 changes: 12 additions & 0 deletions src/commonMain/kotlin/ch/tutteli/kbox/takeIf.kt
Original file line number Diff line number Diff line change
@@ -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 <R> takeIf(predicate: Boolean, provider: () -> R): R? = if (predicate) provider() else null
21 changes: 21 additions & 0 deletions src/commonTest/kotlin/ch/tutteli/kbox/TakeIfSpec.kt
Original file line number Diff line number Diff line change
@@ -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<Int>(false) { throw IllegalArgumentException("bla") }
).toEqual(null)
}

it("it returns null if predicate doesn't hold") {
expect(takeIf(true) { 1 }).toEqual(1)
}
}
})

0 comments on commit feb4f70

Please sign in to comment.