kotlininterfacesetter

Adding custom set method of a property in Kotlin interfaces without referencing a backing field?


I try to implement a custom set method for a property in an interface. How does one do it without referencing a backing field?

interface EmailUser {
  val email: String
  var jina: String
  val nickname: String
    get() = email.substringAfter('@')
  var names: String
    set(value: String) {
        jina = value + "@"}
    }

Solution

  • A property with only a setter is considered to have a backing field. If you also implement a default implementation for the getter, there will be no backing field and the code will compile.

    In this case, an implementation like this could be suitable:

    var names: String
        get() = jina.trimEnd('@')
        set(value) {
            jina = value + "@"
        }