gpt4 book ai didi

Kotlin 数据类 : Why does toString() export private properties

转载 作者:行者123 更新时间:2023-12-02 11:41:34 25 4
gpt4 key购买 nike

这个 Kotlin 数据类

data class PhoneNumber(val prefix: String, private val lineNumber: String)

具有私有(private)属性lineNumber

当我创建一个对象时:

val phoneNumber = PhoneNumber("0676", "123456")
// toString() = PhoneNumber(prefix=0676, lineNumber=123456)

我不希望 toString() 函数也会公开 lineNumber

Joshua Bloch 在《Effective Java》中写道

Provide programmatic access to all of the information contained in the value returned by toString()

如果您不这样做,您的库的客户端将解析 toString() 结果以访问 lineNumber

有人知道为什么 Kotlin 不默认隐藏数据类中 toString() 中的私有(private)属性吗?

最佳答案

我不确定为什么 Kotlin 允许数据类构造函数中的私有(private)属性,但在我看来,对于 data class ,“除了保存数据之外什么都不做的类”,您希望所有数据属性都是公共(public)的并在 equals()hashCode() 中使用, toString(), componentN() functionscopy()

如果不是这种情况,那么我不会将这样的类称为“数据类”,并且 equals()hashCode() 等应该是明确实现。

关于Kotlin 数据类 : Why does toString() export private properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41378186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com