requireNotNull vs sure operator !! in Kotlin

Answer #1 100 %

requireNotNull, assuming you're referring to Objects#requireNonNull, is a Java method that is equivalent to !!, but with a different exception.

You didn't add any code, so it's slightly hard to help you debug. You mentioned third party code quality tools, but not which. I randomly stumbled over this GH issue that matches the error you're having. It's also the only thing I can find that would at any point use that exact error. I might have missed some, but it's the one that covers the top Google hits, so I'm going to go off that.

If you are using Detekt, this is a reported bug. Using !! is even suggested by IntelliJ.

However, you can do it another way.

Yes, using Objects#requireNonNull is one option. There is a second one though, and that's using the null-safe operator, as m0skit0 mentioned.

The reason this works is because if anything called is null, the final result is null. I.e. this:

instance.nonNullType.nullable?.nullableChild?.someOtherNullableChild

If any of the nullable ones are null, the final result is null, and none of the others are called.

Now, considering this is likely a bug in Detect, this seems like the easiest workaround for now:

whatever.calls.you?.make?.to?.the?.database ?: throw NullPointerException("Something is null");

It also keeps the variable non-null, which means you don't need null-safe calls later. The elvis operator checks if anything is null, then throws an exception. Alternatively, you can just use Objects#requireNotNull:

Objects.requireNonNull(whatever.calls.you.make.to.the.database)

If you really need to validate every single step, you'll just need to keep null checks everywhere

TL;DR:

!! and requireNotNull are effectively identical in how they work, except requireNotNull is a method call and !! compiles to an if-statement:

if(whatever == null) {
    Intrinsics.throwNpe();
}

The reason !! triggers UnsafeCallOnNullableType is because of a (probable) bug in Detekt. Both of the options are syntactic sugar for the same thing, though: if the variable is null, throw an NPE.

You’ll also like:


© 2023 CodeForDev.com -