-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #201 from robstoll/feature/takeIf
takeIf as prefix operation
- Loading branch information
Showing
3 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
}) |