what to choose between require and assert in scala

前端 未结 5 1970
谎友^
谎友^ 2020-12-23 13:37

Both require and assert are used to perform certain checks during runtime to verify certain conditions.

So what is the basic difference bet

5条回答
  •  北海茫月
    2020-12-23 13:57

    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.

提交回复
热议问题