gpt4 book ai didi

常规 'assert' : How to display the value?

转载 作者:行者123 更新时间:2023-12-03 13:42:39 28 4
gpt4 key购买 nike

如何在 groovy 中显示一个值是真还是假?我使用 Eclipse 作为我的 IDE。

    assert 4 * ( 2 + 3 ) - 6 == 14 //integers only

而且我也不太了解 Groovy 中的“断言”。它像 Java 中的 if() 语句/ bool 值吗?

“断言”在 Groovy 中扮演什么角色?

最佳答案

断言类似于 if,它验证您提供的表达式:如果表达式为真,则继续执行到下一个语句(并且不打印任何内容),如果表达式为假,则引发 AssertionError。
您可以自定义错误消息,提供由冒号分隔的消息,如下所示:

assert 4 * ( 2 + 3 ) - 5 == 14 : "test failed"
这将打印:
java.lang.AssertionError: test failed. Expression: (((4 * (2 + 3)) - 5) == 14)
但我不得不改变你的测试的值,以使其失败。
断言的使用取决于您的喜好:您可以使用它们来断言在您继续工作之前必须为真的事情(请参阅 design by contract )。
例如。一个需要正数才能使用的函数,可以测试参数为正的事实,将断言作为第一个语句:
def someFunction(n) {
assert n > 0 : "someFunction() wants a positive number you provided $n"
...
...function logic...
}

关于常规 'assert' : How to display the value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12645142/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com