How do I display a value whether it is true or false in groovy? I'm using Eclipse as my IDE.
assert 4 * ( 2 + 3 ) - 6 == 14 //integers only
And also I don't understand 'assert' too well in Groovy. Is it like an if() statement/boolean in Java?
What role does 'assert' play in Groovy?
You can print the current value of a variable with the println function.
An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.
The if's condition needs to be an expression. Assertions are for cases where you want it to fail loudly if what you're asserting is not true. Don't use assert unless you want it to throw an exception if the condition is not met.
An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.
You can customize the error message providing a message separated by a colon like this:
assert 4 * ( 2 + 3 ) - 5 == 14 : "test failed"
which will print:
java.lang.AssertionError: test failed. Expression: (((4 * (2 + 3)) - 5) == 14)
but I had to change the values of your test, in order to make it fail.
The use of assertions is up to your taste: you can use them to assert something that must be true before going on in your work (see design by contract).
E.g. a function that needs a postive number to work with, could test the fact the argument is positive doing an assertion as first statement:
def someFunction(n) { assert n > 0 : "someFunction() wants a positive number you provided $n" ... ...function logic... }
Groovy asserts are now quite impressive! They will actually print out the value of every variable in the statement (which is fantastic for debugging)
for example, it might print something like this if b is 5, a is {it^2} and c is 15:
assert( a(b) == c) . | | | | . 25 | != 15 . 5
(Well--something like that--Groovy's would probably look a lot better).
If we could just get this kind of print-out on an exception line...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With