https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pratik Khandelwal

12/01/2021, 12:04 PM
Hi all, I’m fairly new to Kotlin. I’m trying to implement the below code. The
getCurrentSubscription
method returns a `Subscription?
nullable type. Doing a
.let` makes the
it
also type of
Subscription?
. I though .let should pass on a non-null
Subscription
inside. Now my
cancelSubscription
method expects a non-nullable
it.id
which is causing issues. What am I missing here?
Copy code
getCurrentSubscription.invoke(customerId).let {
      cancelSubscription.invoke(it.id, cancelled).let { subscription ->
        subscriptionApiMapper.fromDomainModel(subscription)
      }
    }
r

Rob Elliot

12/01/2021, 12:12 PM
Use
getCurrentSubscription.invoke(customerId)?.let {
(note the question mark) to have
it
be non-null.
let
just passes the receiver to the lambda, so it can be used on nullable and non-nullable typed receivers. By doing a safe null-dereference (
?.let
) you tell the compiler that the receiver of
let
is definitely not
null
.
👍 1
2 Views