Unfortunately, the bodies of the functions you call, including the built-in functions, are not used for smart casts and nullifications.
There is little that can be improved in your code, and I would suggest only one thing: you can use the Elvis operator with the Nothing function for these statements. Analysis of the control flow takes into account the branches that occur in Nothing and deduces from this zeroing:
fun failOnNull(): Nothing = throw AssertionError("Value should not be null")
val test: Foo? = foo() test ?: failOnNull() // 'test' is not-null after that
It can also be written without a function: test?: throw AssertionError("...") , because the throw expression is also of type Nothing .
Speaking of a more general case of a statement failure, you can use the fail(...): Nothing function, which also provides a hint for analyzing the control flow. JUnit Assert.fail(...) not a Nothing function, but you can find it in kotlin-test-junit or write your own.
test as? SomeType ?: fail("'test' should be an instance of SomeType") // smart cast works here, 'test' is 'SomeType'
hotkey
source share