Home > Blockchain >  Add public getter in Java to protected field in Kotlin?
Add public getter in Java to protected field in Kotlin?

Time:07-20

I am doing some refactoring to a base class in Kotlin. It looks like the following:

abstract class Base constructor (protected val prop: Int) {
   //...
}

I have an implementation in Java that wants to expose prop via a public getter. Is this possible?

public class Impl extends Base {
    public Int getProp() {
        return prop;
    }
}

Causes an error like the following:

Impl.java:269: error: getProp() in Impl cannot override getProp() in Base
    public Int getProp() {
                ^
  overridden method is final

CodePudding user response:

You just have to make getProp overridable, which you can do just by writing

protected open val prop: Int

in the Kotlin code.

  • Related