When should you use a computed getter and when a f...
# getting-started
h
When should you use a computed getter and when a field inside an object returning another const/object? Real world use case:
Copy code
public object GlobalScope : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = EmptyCoroutineContext
}
Why is coroutineContext not a field?
override val coroutineContext = EmptyCoroutineContext
j
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
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
In general, it reduces the memory footprint of the object. So consistent style is not to make constant fields.
h
So you should prefer a getter/function over a field?
c
Unless you’ve got a specific reason for needing it as a field, yeah you’re probably better off preferring the getter
h
Thanks