Search code examples
kotlinoperator-keywordassertionnon-nullable

Allow !! when it is certain it will not throw an NPE


I'm looking at a pull request, which contains !! - the not-null assertion operator. Should it be approved?

The nullable value itself will indeed never be null. I can't think of a better argument than 'It feels wrong'

private val hasFinishedSubject = BehaviorSubject.create<Boolean>()

init {
    hasFinishedSubject.onNext(false)
}

val hasFinishedScanner: Boolean
    get() = hasFinishedSubject.value!!

Since hasFinishedSubject is initialized on construction, hasFinishedSubject.value will never be null

It could be replaced with f.i.:

val hasFinishedScanner: Boolean
    get() = hasFinishedSubject.value ?: false

but this false is redundant and could lead to bugs as well. What is the most clean?


Solution

  • Kotlin compiler respect nullability annotations from Java, e.g. @Nullable or @NotNull from either JSR-305 or intelliJ. https://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations

    It may probably make sense to include these annotations into the BehaviorSubject class if you have control over it.

    From the other side, there are Platform types in Kotlin, that are used to simplify nullability check in Java interop. https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types

    From my point of view, using !! with Kotlin code should be avoided, in Kotlin there are enough ways to make your code Nullable-correct.

    For the Java interop - it may happen. But instead of using !! one may use something more meaningful, like what you suggested above.

    I would probably have written something like:

    val hasFinishedScanner: Boolean
        get() = hasFinishedSubject.value ?: error("No value")
    

    Here the error function has return type Nothing, in fact, it throws an exception.