require和assert有什么区别? [英] What is the difference between require and assert?

查看:456
本文介绍了require和assert有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 Kotlin 1.3 引入了一项新功能,即合同,以及与他们的功能require(),但似乎与assert()非常相似.这是他们的KDoc所说的:

With Kotlin 1.3 came a new feature, contracts, and with them the function require(), but it seems pretty similar to assert(). Here is what their KDoc says:

require(value: Boolean):如果value为假,则抛出IllegalArgumentException.

require(value: Boolean): Throws an IllegalArgumentException if the value is false.

assert(value: Boolean):如果value为false并且使用-ea JVM选项在JVM上启用了运行时断言,则引发AssertionError.

assert(value: Boolean): Throws an AssertionError if the value is false and runtime assertions have been enabled on the JVM using the -ea JVM option.

那么我什么时候应该使用require(),什么时候应该使用assert()?

So when should I use require() and when should I use assert()?

推荐答案

假设您要一个函数来计算 n!(阶乘),如下所示:

Let's say you want a function to calculate n! (factorial) like this:

fun factorial(n: Long): Long {
    require(n >= 0) { "Number must no be negative" }
    // code
}

在这种情况下,require() 检查传递给函数的参数的有效性,如果该参数不符合要求,则抛出一个IllegalArgumentException,对于调试,您也可以进行解释信息.

另一方面,如果已启用运行时断言,则可以在代码中的任何位置使用assert()进行自己的专门检查.

也有 check(Boolean)当其参数为false时抛出IllegalStateException
用于检查对象状态.

因此,以上每种方法在您的代码中都有自己的位置,如果您觉得有用,可以使用它.

In this case require() checks the validity of the argument passed to the function and throws an IllegalArgumentException if the argument is not what it's supposed to be and for debugging you also have the explanatory message.

On the other hand assert() can be used anywhere in your code to make your own specialized checks if runtime assertions have been enabled.

There is also check(Boolean) throws IllegalStateException when its argument is false,
which is used to check object state.

So each of the above has its own place in your code and you can use it if you find it useful.

这篇关于require和assert有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆