Skip to content

Instantly share code, notes, and snippets.

@frgomes
Created February 6, 2019 15:48
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 frgomes/a0fc14d6852029562524bac808aa4c1b to your computer and use it in GitHub Desktop.
Save frgomes/a0fc14d6852029562524bac808aa4c1b to your computer and use it in GitHub Desktop.
def addNaturals(nats: List[Int]): Int = {
require(nats forall (_ >= 0), "List contains negative numbers")
nats.foldLeft(0)(_ + _)
} ensuring(_ >= 0)
@frgomes
Copy link
Author

frgomes commented Feb 6, 2019

We use require for validation of entry conditions and ensuring for validation of exit conditions.

Notice that require is distinct from assert in that, if the condition fails, the caller site is to blame with a IllegalArgumentException, instead of blaming the calle site with an AssertionError.

@frgomes
Copy link
Author

frgomes commented Feb 6, 2019

This is how ensuring is defined in Predef.scala:

  class Ensuring[A](x: A) {
    def ensuring(cond: Boolean): A = { assert(cond); x }
    def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x }
    def ensuring(cond: A => Boolean): A = { assert(cond(x)); x }
    def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment