I am getting comfortable in Kotlin after switching from Java and could not find out how to use Kotlin's assert function in conjunction with an error message.
Sounds simple, I just need something similar to Java's
assert count > 5 : "value too small"
I tried
assert(count > 5, "value too small")
However, the second argument needs to be () -> Any
. How to achieve that?
In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.
The meaning of an AssertionError is that something happened that the developer thought was impossible to happen. So if an AssertionError is ever thrown, it is a clear sign of a programming error.
As with many other languages, the AssertionError in Java is thrown when an assert statement fails (i.e. the result is false). Within today's article we'll explore the detailed of the AssertionError by first looking at where it sits in the larger Java Exception Hierarchy.
Use it to test function arguments. check(Boolean) throws IllegalStateException when its argument is false. Use it to test object state. assert(Boolean) throws AssertionError when its argument is false (but only if JVM assertions are enabled with -ea ). Use it to clarify outcomes and check your work.
assert
's message parameter is not a String, but a function returning a String. This is so because otherwise, since assert
is a normal Kotlin function, its arguments would be evaluated every time which would lead to unnecessary overhead (and sometimes change in semantics) of calculating the message string in case that string is a complex expression.
To pass a function argument, use the lambda syntax. The last argument which is a lambda may be left out of the parentheses:
assert(count > 5) { "value too small" }
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