https://kotlinlang.org logo
Title
h

hfhbd

05/19/2022, 4:13 PM
When should you use a computed getter and when a field inside an object returning another const/object? Real world use case:
public object GlobalScope : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = EmptyCoroutineContext
}
Why is coroutineContext not a field?
override val coroutineContext = EmptyCoroutineContext
j

Joffrey

05/19/2022, 4:16 PM
I don't know a clear answer, but I believe this shouldn't make much difference, especially within an
object
(where any potential saving on object size in memory would likely be insignificant)
c

Casey Brooks

05/19/2022, 4:50 PM
My first thought would be the JVM might be able to optimize this better when coroutineContext is a
get()
function vs a field. Since there are no fields in
GlobalScope
, the JVM may be able to effectively inline the call at runtime to skip the
GlobalScope
class overhead and method call invocation entirely.
d

Dan Fingal-Surma

05/20/2022, 4:08 AM
In general, it reduces the memory footprint of the object. So consistent style is not to make constant fields.
h

hfhbd

05/20/2022, 1:55 PM
So you should prefer a getter/function over a field?
c

Casey Brooks

05/20/2022, 2:02 PM
Unless you’ve got a specific reason for needing it as a field, yeah you’re probably better off preferring the getter
h

hfhbd

05/20/2022, 2:07 PM
Thanks