Vishnu Haridas
11/05/2019, 2:24 PMlet
, also
, apply
etc. to execute some code when the receiver is null?
For example,
val response = getFromUrl(...)
response?.data?.user?.also {
... // welcome the user, save data, and lot more.
} ?: {
showError("Login failed")
} () // IIFE
sindrenm
11/05/2019, 2:27 PMresponse?.data?.user == null
or because the also
block returns null
. It's also less readable than just an if
statement, IMO. I'd do something like this, depending on what you want:
val user = response?.data?.user
if (user != null) {
... // welcome the user, save data, and lot more.
} else {
showError("Login failed")
}
... // welcome the user, save data, and lot more.
returns null
, then you'd also show the error, which is (probably?) not what you want?T.also
returns T
. Then I guess it's not really ambiguous, but still.Vishnu Haridas
11/05/2019, 2:34 PMlet
& also
- both has different outcomes.Perrankana
11/05/2019, 2:34 PMrun
instead of also
in your case, this is how I understand it:`if response, data and user are not null then run a bunch of things`christophsturm
11/05/2019, 2:47 PM?: showError(...)
Vishnu Haridas
11/05/2019, 2:48 PMBurkhard
11/05/2019, 2:49 PM?: run { log("null"); return }
Adam Powell
11/05/2019, 2:53 PMrun {}
instead. run
inlines, the IIFE does not, and will create a class/Function0.invoke call. Much less efficient.sindrenm
11/05/2019, 3:28 PMVishnu Haridas
11/05/2019, 3:39 PM@
🙈 and now only realized that I mentioned someone else 🤦🤦🤦 Updated now ✔️sindrenm
11/05/2019, 3:40 PM