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

Daniele B

08/10/2020, 2:04 PM
Copy code
val resp = webservicesAPI.fetchLatest()
        resp?.let {
            repository.name = resp.name   
            repository.lastUpdate = resp.lastUpdate   
        }
d

diesieben07

08/10/2020, 2:07 PM
The
let
lambda takes a param:
Copy code
fetchlatest()?.let { resp -> 
    repository.lastUpdate = resp.lastUpdate
    // etc
}
d

Daniele B

08/10/2020, 2:08 PM
@diesieben07 thanks! what about if there are 2 lines in the let block, as I just amended ?
d

diesieben07

08/10/2020, 2:09 PM
You can as many lines in the let block as you want, hence why I put "etc" there 😉
👍 1
d

Daniele B

08/10/2020, 2:09 PM
ok, I see! thanks!
m

marstran

08/10/2020, 2:21 PM
This might be just stylistic, but I think
apply
is better here:
Copy code
webservicesAPI.fetchLatest()
  ?.apply {
      repository.name = name   
      repository.lastUpdate = lastUpdate   
  }
✔️ 3
🙅🏻‍♀️ 1
d

Daniele B

08/10/2020, 2:25 PM
@marstran thanks! so is
.apply
running only if
fetchLatest()
returns not null ?
m

marstran

08/10/2020, 2:26 PM
Ah, didn't see the
?
. You still need that. I fixed the code.
d

Daniele B

08/10/2020, 2:26 PM
ok, I see, thanks!
d

diesieben07

08/10/2020, 2:26 PM
No,
apply
is like
let
, except that it uses a lambda wiht receiver instead of a lambda with parameter.
m

marstran

08/10/2020, 2:27 PM
Yes, and it returns the input rather than the return value of the lambda.
d

Daniele B

08/10/2020, 2:27 PM
Copy code
if (remoteData.lastUpdate == null) {
    fetchWeeklyCasesList()
}
do you also have a suggestion to simplify this code?
d

diesieben07

08/10/2020, 2:27 PM
Not sure what you want to simplify about an if statement 🙂 I would say that code is perfectly fine the way it is.
d

Daniele B

08/10/2020, 2:28 PM
maybe writing
?
instead of
null
?
or maybe it can stay like this 🙂
m

marstran

08/10/2020, 2:29 PM
Yes, I think it should stay. The intention is clearer with the explicit null-check.
👍 1
j

Joost Klitsie

08/11/2020, 6:45 AM
Also you can think about creating a mapper, This is a great article on the why and mapping from dto's to domain objects is highly recommended, as, in short, it will make your code better testable. In that case your code could be in the likes of:
Copy code
val repository = webservicesAPI.fetchLatest()?.let { mapper.map(it) }
So I highly recommend reading this: https://proandroiddev.com/the-real-repository-pattern-in-android-efba8662b754
2 Views