null safety : if I `require(foo != null)` then aft...
# announcements
t
null safety : if I
require(foo != null)
then after that the compiles knows foo can't be null. But if I
assertTrue( foo != null)
I have to use
foo?.
or
foo!!.
there after. why is that? Both
require
and
assertTrue
throw exceptions... why can't the compiler figure it for one and not the other? Or is it just a hard-coded list of functions someplace?
t
interesting. didn't know about those. thanks.
but why wouldn't kotlin test libraries not implement them?
r
I don’t know the answer to that.
n
p.s. use
requireNotNull
(or
checkNotNull
)
t
@nanodeath besides the obvious of being more expressive of what is actually happening, is there another reason? I'll use just for that (thank, btw), but curious if there is more to learn.
e
custom contracts are still experimental - meaning that libraries using them may not work in future versions of Kotlin
t
but this feature has been in kotlin a while. before contracts I assume. (or just custom contracts?). How did it work before?
n
contracts were used internally before they were made available externally. I imagine it's compiler magic ("intrinstics"). I mean if you say
require(foo != null)
, all the contract can really say is that require(true/false) should throw or not throw. but if you say requireNotNull(foo), it can actually attach metadata to the foo more directly, such as it not being null
e
checkNotNull()
and
requireNotNull()
also return the non-null item, so it can be used in chains. similar to
!!
but with better messaging