How to extend a data class with toString

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
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)