Francis Mariano
05/09/2024, 6:17 PMJoffrey
05/09/2024, 6:24 PMaction
parameter is defined to return Unit
, so it cannot return T
Joffrey
05/09/2024, 6:25 PMT
and you don't even need a cast, nor the reified
actuallyRuckus
05/09/2024, 6:27 PMFrancis Mariano
05/09/2024, 6:29 PMcrossinline
allows action parameter return UnitRuckus
05/09/2024, 6:30 PMcrossinline
has nothing to do with what it's allowed to return, just when it's allowed to return.Joffrey
05/09/2024, 6:30 PMcrossinline
is just about where you can use the lambda and local returns, it doesn't change the constraints on its typeFrancis Mariano
05/09/2024, 6:31 PMJoffrey
05/09/2024, 6:32 PMT
by calling action()
, though. It's not that you can't declare Unit
as return type. It's just that if you want a T
out of it, it must be declared as such.
In your case, mutex.withLock { action() }
returns whatever action()
returns. So ret
gets the result of action()
.
• If action
is () -> Unit
, then ret
can only be Unit
.
• If action
is () -> T
, then ret
will be of type T
Francis Mariano
05/09/2024, 6:36 PMsuspend inline fun <reified T> execute(crossinline action: () -> T) : T
Joffrey
05/09/2024, 6:38 PMreified
anymore, thoughFrancis Mariano
05/09/2024, 6:38 PMFrancis Mariano
05/09/2024, 6:40 PMFrancis Mariano
05/09/2024, 6:54 PMFrancis Mariano
05/09/2024, 6:54 PMFrancis Mariano
05/09/2024, 7:24 PMsuspend inline fun <reified T> execute(crossinline action: () -> T) : T
the reified is not necessary anymore. Why??Francis Mariano
05/09/2024, 7:28 PMJoffrey
05/09/2024, 7:35 PMT
. Here you don't. You're just getting a value of type T
from the call to action()
, and then returning it from your function (which has return type T
). The implementation of your function doesn't need to know what T
is at compile time, it just needs to know that the value you return matches the return type of the function, which is the case.Joffrey
05/09/2024, 7:37 PMreified
is to get the class of T
using T::class
. Most of the time, this is used to wrap a function that needs a Class<T>
into a function that gets this information from the reified T
. This allows to call myFun<Something>()
instead of myFun(Something::class)
, which looks nicer and more idiomatic.Francis Mariano
05/09/2024, 7:38 PMJoffrey
05/09/2024, 7:39 PM