https://kotlinlang.org logo
Title
z

zak.taccardi

07/29/2019, 6:42 PM
API design question - which would you use to pass around a read-only value that gets initialized once and cached? 1.
suspend () -> T
2.
Deferred<T>
Vote 1️⃣ for
suspend fun () -> T
or 2️⃣ for
Deferred<T>
1️⃣ 7
2️⃣ 4
I see
suspend () -> T
as a more abstract approach, but it requires more boilerplate + some extra anonymous classes
Deferred<T>
has a lot less boilerplate to implement, more clearly indicates that the value will be cached, but it exposes its underlying
Job
API, which a caller could accidentally cancel
o

octylFractal

07/29/2019, 6:45 PM
if you're worried about the cancellation, just create a separate
CompletableDeferred
that's not part of the job.
z

zak.taccardi

07/29/2019, 6:46 PM
CompletableDeferred
extends
Deferred
so it’s worse. This isn’t an API that you would want to allow callers to be able to complete. It’s read only
o

octylFractal

07/29/2019, 6:46 PM
I don't mean return it -- I mean use it to prevent cancellation of the underlying job
you'd still return
Deferred<T>
, but internally you would hand-off the value to create a gap
z

zak.taccardi

07/29/2019, 6:47 PM
oh, very interesting
d

Dominaezzz

07/29/2019, 7:36 PM
Interface version of option 1 I think.
z

zak.taccardi

07/30/2019, 12:25 AM
I’m not a fan of the interface approach as that is less flexible
z

zak.taccardi

07/30/2019, 3:00 PM
interesting idea, but I would like to avoid introducing a custom type
l

louiscad

07/30/2019, 10:58 PM
Well, you can make the top level
val
private, and make a top level suspending function getting the value from it.