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