What is the difference between require and assert?
Asked Answered
P

2

16

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): Throws an IllegalArgumentException if the value is false.

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.

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

Perjure answered 4/11, 2018 at 9:12 Comment(2)
I'm not a Kotlin expert, but it looks like assert is for debugging (that's why you need to run with a flag) and require is to validate the expression.Goggler
The answer is in the question. If you want the verification to always run and throw an IllegalArgumentException, use require. If you want the verification to only run when enabling assertions, and throw an AssertionError, use assert(). require is used to verify that a caller passes the correct arguments. assert is used to verify that your own code doesn't break its own invariants and doesn't have a bug.Downwash
K
23

require and assert work differently. For this, you need to dive into the code.

assert(condition) calls a different method internally, which is where you see the actual code:

@kotlin.internal.InlineOnly
public inline fun assert(value: Boolean, lazyMessage: () -> Any) {
    if (_Assertions.ENABLED) {
        if (!value) {
            val message = lazyMessage()
            throw AssertionError(message)
        }
    }
}

AFAIK, this ties to the -ea flag; if -ea isn't present (or disabled), assert will not throw an exception.

As a result, this will not compile:

fun something(string: String?){
    assert (string != null)
    nonNull(string) // Type mismatch
}
fun nonNull(str: String){} 

This is where require comes in. require(condition) also calls a different method under the hood. If you replace assert with require, you'll see that smart cast will successfully cast it as non-null, because require is guaranteed to throw an exception if the condition fails.

@kotlin.internal.InlineOnly
public inline fun require(value: Boolean, lazyMessage: () -> Any): Unit {
    contract {
        returns() implies value
    }
    if (!value) {
        val message = lazyMessage()
        throw IllegalArgumentException(message.toString())
    }
}

The boolean-only function does the contract too, then calls that method if the contract fails.

Contracts are new, and I am not entirely sure how they work, but this is how I understand it:

The implies keyword is an infix fun; what this does is that it tells the compiler the condition is true if it returns from the method. This helps with auto-casting, like in the example I mentioned earlier. It doesn't actually cause the method to return (or at least that's what my current testing points to), but it's for the compiler.

It's also readable: returning implies condition is true

That's the contact part: the exception here is always thrown, as you can see by the condition. require uses if(!value), where as assert checks if(_Assertions.ENABLED && !value).

This isn't the only use for require though. It can also be used for validation of arguments. I.e. if you have this:

operator fun get(index: Int) : T {
    if (index < 0 || index >= size) 
        throw IllegalArgumentException("Index out of range")
    // return here
}

You could replace it with:

operator fun get(index: Int) : T {
    require (index >= 0 && index < size) { "Index out of range" }
    // return here
}

There are a lot different uses for this, but these are just some examples.

What this means:

  • assert is like in Java; it is only triggered if assertions are enabled. Using it does not guarantee the condition is met.
  • require always works, regardless of VM flags

Which means require can be used to help the compiler with i.e. smart cast, and it's better to use than assert for making sure arguments are valid. And since it also works regardless of VM flags, it can be used outside debugging cases, as forpas mentioned. If you're making a library written in Kotlin, you can replace argument checking with manual throwing with require, and it will still work. Obviously, this assumes Kotlin 1.3.0, but that's beside the point.

And it can be used internally to ensure smart cast works as expected, but throw an exception if the condition isn't met.

To answer your question though:

  • Use require when you want to to argument checking, even if it's in production.
  • Use assert if you're doing local debugging, and have the -ea flag enabled.
Koala answered 4/11, 2018 at 10:48 Comment(1)
May I refine slightly your statement if -ea isn't present (or disabled), assert will not throw an exception. In that case assert not only does not throw the exception, it does not even check the condition.Pedi
M
11

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

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

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.

Mound answered 4/11, 2018 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.