Search code examples
kotlinoverridingdata-class

How to have a data class (Kotlin) extend from a superclass and inherit one of the superclass fields?


I try to create a custom toString() method for some of my data classes. But I would like to define the override of fun toString only once.

This would be my super class:

abstract class Id(val value: String) {
   override fun toString(): String {
       return value
   }
}

Now I want to use the customised toString() method in some of my data classes by extending the superclass Id:

data class MyId(val v: String): Id(v)

however, this would introduce a secondary field and getter for "v" in MyId, which is not what I want. Using "value" instead of "v" gives me the issue: 'value' hided a member of supertype 'Id'. I would like to reuse the "value" field and getter, defined in Id. I do not want to introduce a new one.

How can I correct this?


Solution

  • I'm not quite sure what you are trying to do, but you can do this

    abstract class Id(open val value: String) {
        override fun toString(): String {
            return value
        }
    }
    
    data class MyId(override val value: String): Id(value)