Skip to content

Instantly share code, notes, and snippets.

@jcaromiq
Last active August 6, 2018 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcaromiq/7e4a9ae32a30be329d4345cb43367f89 to your computer and use it in GitHub Desktop.
Save jcaromiq/7e4a9ae32a30be329d4345cb43367f89 to your computer and use it in GitHub Desktop.
fun <R> Boolean.fold(whenFalse: R, whenTrue: R) = when (this) {
true -> whenTrue
false -> whenFalse
}
inline fun <R> Boolean.fold(whenFalse: () -> R, whenTrue: () -> R) = when (this) {
true -> whenTrue()
false -> whenFalse()
}
import org.assertj.core.api.Assertions.*
import org.junit.jupiter.api.Test
class FoldableBooleanTest {
@Test
fun should_return_true_parameter_when_fold_over_true() {
val trueValue = true
val should = trueValue.fold("It's false", "It's true")
assertThat(should).isEqualTo("It's true")
}
@Test
fun should_return_false_parameter_when_fold_over_false() {
val falseValue = false
val should = falseValue.fold("It's false", "It's true")
assertThat(should).isEqualTo("It's false")
}
@Test
fun should_apply_true_function_when_fold_over_true() {
val trueValue = true
trueValue.fold({ throw Exception() }, { assertThat(true).isTrue() })
}
@Test
fun should_apply_false_function_when_fold_over_true() {
val falseValue = false
falseValue.fold({ assertThat(true).isTrue() }, { throw Exception() })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment