Just when I thought I understood it, I got the following issue.
I have a base class in another module (called base here)
It looks like that:
open class BaseTest {
companion object {
lateinit var baseTest: BaseTest
}
protected open var someProperty: String? = "base"
}
I want to set that property and made it protected so my extended class in another module could access it.
class Extended: BaseTest() {
fun extendedCall() {
BaseTest().someProperty = "extended"
baseTest.someProperty = "extended"
}
}
However, neither the static one, not the direct property is accessable stating the following error:
Cannot access 'someProperty': it is protected in 'BaseTest'
But shouldn't that be accessable since Extended inherents from BaseTest()? I mean the definition of protected is "Declarations are only visible in its class and in its subclassess" so what have I missed? It even doesn't work in the same module so that's not the cause.
What am I missing?
CodePudding user response:
BaseTest().someProperty = "extended"
Here you make a new BaseTest object by calling the constructor BaseTest()
and you are not allowed to access protected properties of other BaseTest objects.
baseTest.someProperty = "extended"
the static BaseTest object is also another object and not the Extended object itself.
Being protected merely makes it possible to do
someProperty = "extended"
or the equivalent
this.someProperty = "extended"
That is, access the property of this object.
CodePudding user response:
I believe the protected
modifier doesn't work like that in Kotlin.
The documentation says:
The protected modifier is not available for top-level declarations.
But I agree it's quite confusing as written. It appears the documentation focuses more on the Outter/Inner class relationship via the this
keyword.