I mean, should I only use !! if dealing with legac...
# server
l
I mean, should I only use !! if dealing with legacy code?
n
Typically it is best to avoid using !! whenever possible. The main exception is testing where it is much better to discover issues early on rather than in production.
a
Sometimes auto-casting is not picked up, I did a not null check, further on I use the var/val my editors says it could be null. In those cases I use
!!
👍 1
a
@Albert Think that should only occur with
var
where the variable may have been modified between the check for not null & it’s usage
a
@andyb I also use it for nullable
val
on a class.
Copy code
example(someClass: SomeClass) {
  if (someClass.nullableField == null) {
    throw SomeSpecificException()
  }
}

lookUp(someClass.nullableField!!)
The example might be weird, but I need this for an application to throw specific exceptions when this occurs. Assigning it to a local
val
will fix this, but this is only to demonstrate
d
@Albert Be aware that the reason it doesn't autocast the property there is because it could be modified by another thread. For thread safety, you should use a
val
to only read the property one time. For example:
val nullableField = nullableField ?: throw SomeSpecificException()
б