Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin protected property can not be accessed in other module

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

    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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading