in kotlin, how to access protected static member in parent class from sub class

Viewed 134

It is code worked in java but after convert to kotlin it does not compile.

Having a base class which has some defines as static protected member in the companion object:

abstract class ParentClass {

   companion object {
        @JvmField
        final protected val SERVICE_TYPE_A = "the_service_type_a"    
   }
}

and the child class:

class ChildClass: ParentClass {
    public override fun getServiceType(): String {
        return SERVICE_TYPE_A. //<== got compile error
    }
}

it does not compile.

how to access a parent class static protected member from subclass?

enter image description here

1 Answers

You need to use @JvmStatic instead as follows:

abstract class ParentClass {
    companion object {
        @JvmStatic
        protected val SERVICE_TYPE_A = "the_service_type_a"
    }

    abstract fun getServiceType(): String
}

The final keyword in SERVICE_TYPE_A is redundant since everything is final by default in Kotlin. This also mean that if you want ParentClass to be extended, then you need to explicitly define it as open.

Then your ChildClass would look as follows:

class ChildClass: ParentClass() {
    override fun getServiceType(): String {
        return SERVICE_TYPE_A
    }
}
Related