如何使用toString扩展数据类 [英] How to extend a dataclass with toString
问题描述
我已经创建了一个数据类
I have created a dataclass
data class Something (
val a : String,
val b : Object,
val c : String
)
稍后在我的程序中,我需要尝试扩展toString方法的该数据类的字符串表示形式.
as later in my program I need the string representation of this dataclass I tried to extend the toString method.
override fun Something.toString() : String = a + b.result() + c
这里的问题是,它不允许扩展(覆盖)toString函数,因为它不适用于顶级函数.
The problem here is, it does not allow extending(overriding) the toString funtion, as it is not applicable to top level functions.
如何正确覆盖/扩展自定义数据类的toString方法?
How to properly override/extend the toString method of a custom dataclass?
推荐答案
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.
但是在您的情况下,没有什么能阻止您覆盖Something
类主体内的toString
,因为data
类可以具有与常规类一样的主体:
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
}
这篇关于如何使用toString扩展数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!