Search code examples
kotlinkotlin-null-safety

Combine null safety and assertNotNull


In test we usually have assertNotNull, but it does not perform smart cast from a nullable type to a non-nullable. I have to write something like this:

if (test == null) {
    Assert.fail("")
    return
}

Is it a workaround to perform smart cast only with assertNotNull call? How do you deal with it?


Solution

  • Unfortunately, the bodies of the functions that you call, including inline functions, are not used for smart casts and nullability inference.

    There's not much in your code that can be improved, and I would only suggest one thing: you can use the Elvis operator with a Nothing function for those assertion statements. The control flow analysis takes into account the branches resulting into Nothing and infers nullability from that:

    fun failOnNull(): Nothing = throw AssertionError("Value should not be null")
    

    val test: Foo? = foo()
    
    test ?: failOnNull()
    // `test` is not-null after that
    

    This can be written without a function as well: test ?: throw AssertionError("..."), because a throw expression also has type Nothing.


    Speaking of a more general case of failing an assertion, one might use a fail(...): Nothing function, which provides a bonus hint for the control flow analysis as well. The JUnit Assert.fail(...) is not a Nothing function, but you can find one in the kotlin-test-junit module or write your own one.

    test as? SomeType ?: fail("`test` should be an instance of SomeType")
    // smart cast works here, `test` is `SomeType`