what are the two exclamation marks `!!` at the end...
# getting-started
n
what are the two exclamation marks
!!
at the end ^^^ ?
n
thanks @Shawn. So not sure why @df explicitly used
!!
in
return _fulfillmentDetails!!
... What would he gain ? And how would it change if he didn't use
!!
?
s
That’s a little complicated to answer - in this example, I presume
_fulfillmentDetails
is a a private, nullable type, and the getter that they pasted in exposes a public, non-null type
this is sometimes done as a hacky way to lazily evaluate properties, which is why a lazy delegate is suggested in the thread
but more to the point, because
_fulfillmentDetails
is a nullable
var
and smart-casting cannot safely determine that it contains a non-null value in this instance, you have to tell the compiler to assert that the value is not null, or throw an NPE
an expanded example might look like this :
Copy code
class Example {
  private var _fulfillmentDetails: FulfillmentDetails? = null

  public val fulfillmentDetails: FulfillmentDetails
    get() {
      if (_fulfillmentDetails == null) {
        _fulfillmentDetails = FulfillmentDetails(this)  // initialize on first usage
      }
      return _fulfillmentDetails!!  // need to assert/convert to non-nullable type since the declared type is non-nullable
    }
}
without
!!
this would be a compile error
but there are ways to do this that don’t involve that operator
n
thanks a lot @Shawn!
👍 2
d
And in case you are not sure why I could be null even though it was assigned the line before you need to think about multi threaded environments where a different thread could change the value back to null in-between
2