How to extend a dataclass with toString

 ̄綄美尐妖づ 提交于 2019-11-29 09:04:17

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!