Both require
and assert
are used to perform certain checks during runtime to verify certain conditions.
So what is the basic difference bet
This is only my subjective point of view.
I use require
whenever I want a constraint on parameters.
As an example we can take the factorial for natural numbers. As we do not want to address negative numbers, we want to throw an IllegalArgumentException
.
I would use assert
, whenever you want to make sure some conditions (like invariants) are always true during execution. I see it as a way of testing.
Here is an example implementation of factorial with require
and assert
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)
}
When result > 1
is true, then the loop was executed at least once. So the result has to be bigger or equal to k
. That would be a loop invariant.
When you are sure that your code is correct, you can remove the assert
, but the require
would stay.