Require and assert in Scala

Source: Internet
Author: User
Tags assert
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)
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.