How to extend dataclass using toString

I created a dataclass

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

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

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

The problem is that it does not allow you to extend (override) the toString function, since it is not applicable to top-level functions.

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

+11
source share
1 answer

In Kotlin, extension functions cannot override member functions; moreover, they are statically allowed . This means that if you write the fun Something.toString() = ... extension function fun Something.toString() = ... , s.toString() will not be allowed to it, because the member always wins .

But in your case, nothing prevents you from overriding toString inside the Something body, because data classes can have bodies similar to regular classes:

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

All Articles