I was exploring, chasing implementors of functions...
# compose
t
I was exploring, chasing implementors of functions I was playing with, and stumbled on this from the Compose sources:
Copy code
@Composable
@ReadOnlyComposable
internal fun resources(): Resources {
    LocalConfiguration.current
    return LocalContext.current.resources
}
I was surprised to see the first line of the function body there. It simple accesses LocalConfiguration.current, but does nothing with it? Why is this line there? If it's causing an undocumented state change side effect through a simple access, that seems to fly in the face of what Compose is about? And does that mean that the Kotlin compiler will never optimize that sort of thing away? (A C compiler would look at it and see, huh, didn't do anything with the result, skipping the whole thing, unless otherwise informed (e.g. volatile, etc))
s
It subscribes to changes in configuration, so that resources are recalculated whenever configuration changes.
Also "didn't do anything with the result" doesn't matter since this is a property getter call that can cause side effects. I agree that field getter can be optimized this way (not sure Kotlin really does), but usually these types of optimizations happen at runtime where JIT compiler can actually prove no side effects occur.
a
It’s a good thing if you’re looking at that code and thinking “this feels really weird” - this side-effect from reading one thing, to cause requerying something else is super strange and should probably raise your suspicions if you are encountering it often
t
I'm a big fan of "let the code tell it's story if possible" (e.g. less comments), but I was surprised there wasn't a comment here for this
a
There is a comment on the function saying exactly what it does though?
Copy code
* A composable function that returns the [Resources]. It will be recomposed when [Configuration]
* gets updated.