Melvin Biamont
11/04/2019, 2:00 PMinline functions
.
How can I make an inline function stopping/returning the calling function?
Basically, I would like this :
//This method should return the calling function
inline fun onUserNull() = run {
Timber.e("User is null")
return
}
fun fetchUserIdentity() {
val currentUser = userDataSource.currentUser ?: onUserNull()
presenter.displayUserIdentity(currentUser)
}
Would do the same as:
fun fetchUserIdentity() {
val currentUser = userDataSource.currentUser ?: run {
Timber.e("User is null")
return
}
presenter.displayUserIdentity(currentUser)
}
Alowaniak
11/04/2019, 2:57 PMval currentUser = userDataSource.currentUser ?: return Timber.e("User is null")
louiscad
11/04/2019, 3:13 PMNothing
, then at use site, you can put return
in that lambda argument.Melvin Biamont
11/04/2019, 3:14 PMinline functions
content are more or less just copied in the call site.
So, why couldn’t I do return
from an inline function?Nothing
? From what I read, the only way is to throw an exception, which is not what I wanted.louiscad
11/04/2019, 3:16 PMreturn
evaluates to Nothing
too 😉return
expression already evaluates to `Nothing`: it makes code below unreachable.Melvin Biamont
11/04/2019, 3:37 PMinline fun reportUserNull(): Nothing {
Timber.e("User is null")
return
error("user is null")
}
But, it tells me This function must return a value of type Nothing
I think I can’t just use return
😕inline fun reportUserNull(): Nothing {
Timber.e("User is null")
return error("user is null")
}
Like this seems okay.
(I’ll try it)error("user is null")
is reachable ˆˆAlowaniak
11/04/2019, 3:45 PMreturn
in the caller via for example a lambda) other than throwing an exception?
The reason why I would say you shouldn't want it in the first place is because IMO it would get totally unclear what happens at call-site
Also I'm not sure but I don't think an inline
function is always inlined (for example when calling from java, or when function is virtual)
I really think you should just do
val x = foo ?: return onBar()
or
val x = foo ?: onBar().also { return }
louiscad
11/04/2019, 3:46 PMinline fun returnFromMyLambda(returnYourself: () -> Nothing) {
stuff()
if (shouldDoIt) returnYourself()
}
fun computeNumber(): Int {
if (Random.nextBoolean()) {
return 1 + 1
} else {
returnFromMyLambda {
return 0 + 3 // returns from computeNumber
}
}
}
Melvin Biamont
11/04/2019, 3:49 PMlouiscad
11/04/2019, 4:34 PMUnit
, so would put return type constraints on the caller).czuckie
11/05/2019, 8:00 AMMelvin Biamont
11/05/2019, 3:40 PM