Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
734 views
Welcome To Ask or Share your Answers For Others

1 Answer

In Kotlin, extension functions cannot override member functions, moreover, they are resolved statically. It implies that if you write an extension function fun Something.toString() = ..., s.toString() won't be resolved to it, because member always 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...