Skip to content

Instantly share code, notes, and snippets.

@pambrose
Last active July 2, 2022 22:05
Show Gist options
  • Select an option

  • Save pambrose/52307b51f6bcda5b6c2682c760c8bbf6 to your computer and use it in GitHub Desktop.

Select an option

Save pambrose/52307b51f6bcda5b6c2682c760c8bbf6 to your computer and use it in GitHub Desktop.
Kotlin pre and post conditions
// Out-of-the-box require() stmts
fun increment1(x: Int): Int {
require(x > 0) { "value must be positive" }
return (x + 1).also { require(it > 0) { "result is positive" } }
}
// Consolidate the post also/require() stmts into ensure()
fun increment2(x: Int): Int {
require(x > 0) { "value must be positive" }
return (x + 1).ensure({ it > 0 }) { "result is positive" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment