与断言相比,scala中的假设是什么意思? [英] What is the meaning of an assumption in scala compared to an assertion?
问题描述
Scala似乎定义了3种断言:assert
,require
和assume
.
Scala seems to define 3 kinds of assertions: assert
, require
and assume
.
据我了解,require
的区别(与一般断言相比)是它专门用于检查输入(参数,传入消息等).那么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?
推荐答案
如果查看Predef.scala
中的代码,您会发现这三个代码都做得非常相似:
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")
}
还有一些版本出于报告目的采用了额外的参数(请参见 http://harrah.github.com/browse/samples/library/scala/Predef.scala.html ).
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.
但是,静态检查器可以对所有这三个方法进行不同的处理.目的是让assert
指定一个条件,该条件应尝试进行静态检查,而assume
将用于确定检查者可能认为要保持的条件,而require
则指定调用者必须确保的条件. .如果静态检查者发现违反assert
的行为,则认为它是代码中的错误,而当违反require
的行为时,则认为调用者有错误.
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.
这篇关于与断言相比,scala中的假设是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!