Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Error Message from assertion in Kotlin

Tags:

assert

kotlin

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?

like image 861
linqu Avatar asked May 10 '16 14:05

linqu


People also ask

How do you throw an assertion error?

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.

What is the assertion error?

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.

What causes Java Lang AssertionError?

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.

What is assertion in Kotlin?

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.


1 Answers

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" }
like image 195
Alexander Udalov Avatar answered Nov 14 '22 20:11

Alexander Udalov