68

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?

4

1 回答 1

122

在 Kotlin 中,扩展函数不能覆盖成员函数,而且它们是静态解析的。这意味着如果您编写扩展函数fun Something.toString() = ...s.toString()将不会被解析为它,因为成员总是会获胜

但在你的情况下,没有什么能阻止你toStringSomething类体内覆盖,因为data类可以像普通类一样拥有主体:

data class Something(
    val a: String,
    val b: Any,
    val c: String
) {
    override fun toString(): String = a + b + c
}
于 2016-03-13T13:47:21.057 回答