How to extend a data class with toString

KotlinKotlin ExtensionData Class

Kotlin Problem Overview


I have created a data class

data class Something (
    val a : String,
    val b : Object,
    val c : String
)

as later in my program, I need the string representation of this data class I tried to extend the toString method.

override fun Something.toString() : String = a + b.result() + c

The problem here is, it does not allow extending (overriding) the toString function, as it is not applicable to top-level functions.

How to properly override/extend the toString method of a custom dataclass?

Kotlin Solutions


Solution 1 - Kotlin

Adding a .toString() extension function would not work because:

  • Extension functions can't take part in virtual calls (they are resolved statically). In other words, extensions cannot override member functions.
  • If there is a matching member function, it is preferred to the extension. If you add an extension function fun Something.toString() = ..., then s.toString() won't be resolved to it, because the corresponding member inherited from Any wins.

But in your case, nothing stops you from overriding toString inside Something class body, because data classes can have bodies just like regular classes:

data class Something(
    val a: String,
    val b: Any,
    val c: String
) {
    override fun toString(): String = a + b + c
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAleksandarView Question on Stackoverflow
Solution 1 - KotlinhotkeyView Answer on Stackoverflow