Issue
I am trying to access a property reference, but this error comes:
Backing field of 'var sInstance: Any' is not accessible at this point
I know that it is possible to access a static property from a non-static context (not the other way around, though). Is it any different with property references? Why? What can I read to gain a better understanding of how this mechanism works to be able to explain to myself why this code is not allowed to compile?
class Example {
companion object {
lateinit var sInstance: Any
}
fun func() {
if (!::sInstance.isInitialized) {
sInstance = Any()
}
}
}
Now, I am not primarily trying to get it working like in this question (let alone that their case differs from mine), I am trying to gain knowledge. And I don't know what to start with. Again, their question is aimed at solving the issue by any means, not providing a deeper understanding of the mechanism. I want to know why I can't access a static property's property reference's isInitialized
field from a non-static context.
Although, I am allowed to use isOpen
, isLateinit
, isConst
, isSuspend
, isAbstract
, isFinal
fields if I replace isInitialized
in my example with one of them. Perhaps it has something to do with KProperty0
or @receiver:AccessibleLateinitPropertyLiteral
(read down below)? Where do I go from here to know more?
From the documentation (the Lateinit.kt
file):
@SinceKotlin("1.2")
@InlineOnly
inline val @receiver:AccessibleLateinitPropertyLiteral KProperty0<*>.isInitialized: Boolean
get() = throw NotImplementedError("Implementation is intrinsic")
Solution
You can't access it because isInitialized
is deep magic. That source file you link is useless, as isInitialized
is baked far deeper into the compiler. The documentation specifically tells us when we're allowed to access it.
This check is only available for properties that are lexically accessible when declared in the same type, in one of the outer types, or at top level in the same file.
Your property is not declared in the same type. The property is declared in Example.Companion
(a type which is sometimes permitted to be abbreviated to Example
), whereas your attempted check is being done in Example
. Example.Companion
is not an outer class of Example
, nor is it the top-level scope, so it's not allowed.
There isn't any deeper meaning here, and it has nothing to do with static vs. non-static (which is terminology you should probably disabuse yourself of, as Kotlin does not have a static
keyword and instead uses the companion object abstraction). It's just a very specific compiler special case that has special access rules.
Answered By - Silvio Mayolo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.