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

Ivan picture Ivan · Nov 3, 2011 · Viewed 9.8k times · Source

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

As far as I can understand, the difference (compared to a generic assertion) of require is that it is specifically meant for checking inputs (arguments, incoming messages etc). And what's the meaning of assume then?

Answer

Adam Zalcman picture Adam Zalcman · Nov 3, 2011

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.