Unwrapping optionals in Kotlin

In Kotlin, there are several ways to unwrap an optional value:

  1. The ?: operator, also known as the Elvis operator, can be used to provide a default value if the optional is null. For example: val x = optionalValue ?: 0.
  2. The let function can be used to execute a block of code if the optional is not null. For example: optionalValue?.let { doSomething(it) }.
  3. The ?. operator, also known as the safe call operator, can be used to access a property or call a function on an optional without causing a null pointer exception. For example: optionalValue?.property or optionalValue?.function().
  4. The !! operator, also known as the not-null assertion operator, can be used to force the optional to have a value. This should be used with caution, as it will throw a null pointer exception if the optional is null. For example: val x = optionalValue!!.
  5. The ifPresent method can be used to execute a block of code if the optional is not null. For example: optionalValue.ifPresent { doSomething(it) }.
  6. let with ?: can be used to execute a block of code if the optional is not null and provide a default value if it is. For example: optionalValue?.let { doSomething(it) } ?: defaultValue