How idiomatic is using an Immediately Invoked Func...
# announcements
v
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
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
@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
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
why do you need the function at all, why not
?: showError(...)
โž• 1
v
@christophsturm true for a single line, but for a block of code, don't we need an IIFE?
b
One example is
?: run { log("null"); return }
a
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
I am a little curious as to who Stephan Schroeder is and what they have to do with this. ๐Ÿ˜ฎ
๐Ÿ˜„ 1
v
@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
Oh well, now they can get in on the fun, too! ๐ŸŽ‰ Made me think of this https://kotlinlang.slack.com/archives/CJLTWPH7S/p1572635193281700?thread_ts=1572624750.257500&cid=CJLTWPH7S
๐Ÿ˜„ 1