https://kotlinlang.org logo
#announcements
Title
# announcements
v

Vishnu Haridas

11/05/2019, 2:24 PM
How idiomatic is using an Immediately Invoked Function Expression (IIFE) with an Elvis after
let
,
also
,
apply
etc. to execute some code when the receiver is null? For example,
Copy code
val response = getFromUrl(...)

response?.data?.user?.also {
    ...  // welcome the user, save data, and lot more.
} ?: {
    showError("Login failed")
} ()  // IIFE
s

sindrenm

11/05/2019, 2:27 PM
Not my preference. It's unclear if it's invoked because
response?.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:
Copy code
val user = response?.data?.user

if (user != null) {
   ...  // welcome the user, save data, and lot more.
} else {
  showError("Login failed")
}
☝️ 2
Of course, in your example, if
Copy code
...  // welcome the user, save data, and lot more.
returns
null
, then you'd also show the error, which is (probably?) not what you want?
Or … no, sorry, my bad.
T.also
returns
T
. Then I guess it's not really ambiguous, but still.
v

Vishnu Haridas

11/05/2019, 2:34 PM
@sindrenm Got it! from your first answer, the ambiguity really depends upon the Scope function that we use. For example
let
&
also
- both has different outcomes.
👍 1
p

Perrankana

11/05/2019, 2:34 PM
I would use
run
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`
👍 2
c

christophsturm

11/05/2019, 2:47 PM
why do you need the function at all, why not
?: showError(...)
1
v

Vishnu Haridas

11/05/2019, 2:48 PM
@christophsturm true for a single line, but for a block of code, don't we need an IIFE?
b

Burkhard

11/05/2019, 2:49 PM
One example is
?: run { log("null"); return }
a

Adam Powell

11/05/2019, 2:53 PM
IIFE isn't a thing in kotlin, use
run {}
instead.
run
inlines, the IIFE does not, and will create a class/Function0.invoke call. Much less efficient.
❤️ 1
👀 1
(you can verify this with the, "show kotlin bytecode" view in intellij/android studio)
s

sindrenm

11/05/2019, 3:28 PM
I am a little curious as to who Stephan Schroeder is and what they have to do with this. 😮
😄 1
v

Vishnu Haridas

11/05/2019, 3:39 PM
@sindrenm actually I meant you only 😐 I hit enter as soon as I typed
@
🙈 and now only realized that I mentioned someone else 🤦🤦🤦 Updated now ✔️
s

sindrenm

11/05/2019, 3:40 PM
😄 1
12 Views