Require means that the caller of the method is at fault and should fix its call. Use require whenever you want a constraint on parameters, and throw an IllegalArgumentException.
2. Assert
Assert means that your program has reached an inconsistent state this might be a problem with the current method/function.
You can use an assert to verify all the invariants everywhere in your program (all the preconditions/postconditions for every single method/function calls) and not pay the price in production.
def fac(i: Int) = { require(i >= 0, "i must be non negative") //this is for correct input @tailrec def loop(k: Int, result: Long = 1): Long = { assert(result == 1 || result >= k) //this is only for verification if(k > 0) loop(k - 1, result * k) else result } loop(i) }
Reference: http://stackoverflow.com/questions/26140757/what-to-choose-between-require-and-assert-in-scala
No comments:
Post a Comment