Unwrapping optionals in Kotlin
Unwrapping optional type is different in Kotlin. Let's check all possible ways.
In Kotlin, there are several ways to unwrap an optional value:
- 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
. - The
let
function can be used to execute a block of code if the optional is not null. For example:optionalValue?.let { doSomething(it) }
. - 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
oroptionalValue?.function()
. - 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!!
. - The
ifPresent
method can be used to execute a block of code if the optional is not null. For example:optionalValue.ifPresent { doSomething(it) }
. 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