What is the meaning of an assumption in scala compared to an assertion?

后端 未结 3 579
悲哀的现实
悲哀的现实 2021-01-31 07:44

Scala seems to define 3 kinds of assertions: assert, require and assume.

As far as I can understand, the difference (compared to a

3条回答
  •  日久生厌
    2021-01-31 08:38

    If you look at the code in Predef.scala you'll see that all three do very similar job:

    def assert(assertion: Boolean) { 
      if (!assertion) 
        throw new java.lang.AssertionError("assertion failed") 
    } 
    
    def assume(assumption: Boolean) { 
      if (!assumption) 
        throw new java.lang.AssertionError("assumption failed") 
    } 
    
    def require(requirement: Boolean) { 
      if (!requirement) 
        throw new IllegalArgumentException("requirement failed") 
    } 
    

    There are also versions which take extra arguments for reporting purposes (see http://harrah.github.com/browse/samples/library/scala/Predef.scala.html).

    The difference is in the exception type they throw and error message they generate.

    However, static checkers could treat all three differently. The intention is for assert to specify a condition that a static check should attempt to prove, assume is to be used for a condition that the checker may assume to hold, while require specifies a condition that the caller must ensure. If a static checker finds a violation of assert it considers it an error in the code, while when require is violated it assumes the caller is at fault.

提交回复
热议问题