When is it best to use `!!` over `checkNotNull`?
# stdlib
d
When is it best to use
!!
over
checkNotNull
?
☝️ 1
d
!!
will throw an NPE without any context. Use
require
and
check
when validating preconditions, throwing IllegalArgument/StateException with a message of your choosing because you have external callers or want to carry more context with the message
Use
require*
for incoming function arguments
Of course if a function argument value should never be null, don't allow it to be nullable and you get the nullability check at runtime automatically
g
so, not a real difference unless you provide a custom message?
d
NullPointerException vs IllegalArgument/IllegalStateException, but no, still fails fast - I wonder if the compiler has optimizations for argument nullability checks though
q
Kotlin compiler is not that smart optimization wise