Require and assert in Scala
Both require and assert are used to perform certain checks at run time to verify certain conditions.
So what is the difference between them? Assert means that your program has reached an inconsistent state, which may be a problem with the current method/function (I like to think of it as an HTTP Internalservererror) require means there is a problem with the caller of the method. Should fix its call (I like to think of it as HTTP badrequest)
Assert with @elidable (assertion) annotation, which means that you can use-xelide-assertion or-xdisable-assertions to compile your program, the compiler will not generate bytecode for this assertion. If you have a large number of assertions, this can significantly reduce the size of bytecode and improve performance.
Knowing this, you can use Assert to verify all the invariant in the program (all prerequisites/post conditions for each method/function call), rather than paying the price in the "official" version.
Typically, the test version enables all the Assert, which is slow because it verifies all the assert at any time, and then compiles the "official" version without an assert.
Require is not canceled and is used in libraries (including internal libraries) to inform callers of the prerequisites for invoking a given method/function, for example, to restrict certain parameters. This is very meaningful for developers.
def FAC (i:int) = {
require (I >= 0, "I must be non negative")//this was for correct input
@tailrec def loop (k: Int, Result:long = 1): Long = {
assert (result = = 1 | |-result >= k)//this be only for verification
if (K &G T 0 Loop (k-1, result * k) Else result
}
Loop (i)
}