How does everyone feel about the answer from <@U09...
# announcements
c
How does everyone feel about the answer from @yole here? I personally really like using !! when I want to assert that something is not null at that point. https://discuss.kotlinlang.org/t/requirenotnull-or/1562/2
s
It provides a shitty debugging experience without any reason for the error
👆 1
I try to never use
!!
in my code
👍 3
m
Using
requireNotNull
expresses intent more clearly.
👍 1
s
Agree in avoiding bang-bang (unless it's a reference to Jessie J, Ariana Grandle and Nicki Minaj).
requireNotNull
and
checkNotNull
express intent more clearly, or when it makes sense just using `if`s with smart-casting. 😎
😆 1
b
The one place i use
!!
is to tell kotlin that a platform type is not null, e.g.
someJavaCall()!!
e
I read
!!
as “require not null”
c
@elizarov thoughts on this post? https://fragmentedpodcast.com/episodes/176/
Donn walks through why Kotlin’s Not Null Assertion Operator (!!) is a code smell and what you can do to alleviate it.
e
Have not listened to it. Is there a transcription available?
c
Unfortunately not. 😭
c
The podcast basically says never to use
!!
, except maybe in tests.
I think it’s a bit too strong, there are cases even in production code where things should absolutely never be
null
(e.g. a configuration file should be part of the distribution). Your app is going to crash if that thing is
null
, so it’s all a matter of how you want to crash.
c
Yeah. @cedric personally I prefer to crash if I know it should never be null, but it sounds like the podcast author uses some other techniques, but I haven't found anything as easy to use as !!.
e
You can use
?: error("This should not happen")
. I guess a project might have a policy to provide a better message that includes a context in this case. That would be a material improvement over
!!
. Without additional context in a message I see no benefit in writing longer code, though.
s
The “better error” part here is also a reason why I prefer `requireNotNull`/`checkNotNull` over
!!
. 👍
s
How do you remember which is which ?
s
require
vs
check
? I … don't know, I guess I just remember that
require
is in the context of arguments, where
check
is in the context of state, but I'm not sure why. 😛
c
@sindrenm I tried to just do a requireNotNull check, but it didn't do anything because my value was mutable, so I still had to use !! or ? in line when accessing the variable.
s
requireNotNull<T?>
returns the
T
(non-nullable, so you could potentially do this:
Copy code
val value = requireNotNull(nullableValue)

// use value henceforth
Or, you could also inline the
requireNotNull(value)
calls to wherever you're accessing
value
, but I often find it nicer to just put it in a local
val
and “be done with it”.