Skip to content

Instantly share code, notes, and snippets.

@frgomes
Created February 6, 2019 15:48
Show Gist options
  • 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

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