Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
Feeco Avatar asked Feb 05 '17 03:02

Feeco


People also ask

IS null safety good?

Sound null safety is a great feature that allows Dart to catch up with other languages like Kotlin and Typescript. It reaffirms that Dart is a developer happiness-focused language.

What is null safety in programming?

Void safety (also known as null safety) is a guarantee within an object-oriented programming language that no object references will have null or void values. In object-oriented languages, access to objects is achieved through references (or, equivalently, pointers).

What are null safety and nullable types in Kotlin?

Nullable and Non-Nullable Types in Kotlin –Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.


1 Answers

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`
like image 128
hotkey Avatar answered Sep 22 '22 06:09

hotkey