How to implement getter

I have an java interface in a library:

public interface ObjectWithId() {
  Long getId();
}

How can I implement this interface in Kotlin class?

class TestObject : ObjectWithId {
  public var id : Long? = null
}


causes error: Accidental override

I tried different ways to implement the interface but no success:

class TestObject : ObjectWithId {   var id : Long? = null   override fun getId() : Long? =id

}

class TestObject : ObjectWithId {   var id : Long? = null   override get

}

Things to take a not of:

  • Java getters are not seen as property accessors from Kotlin (this is why simply overriding with a property named "id" does not work). This may be enhanced in the future, though.
  • Non-private Kotlin properties produce getters (and setters in case of vars) named "get<capitalized-property-name>", i.e. in your case "getId" (this is why you can't define "getId" function alongside with a non-private property "id")

So, one way of achieving what you want is:

class TestObject : ObjectWithId {   private var id : Long? = null // private

  override fun getId() : Long? =id

}


If you really have to have a non-private property, then you need a different name for it (we will support changing platform names for final class members eventually, but curretly it is not possible).

1 Like