【发布时间】:2019-08-24 07:45:51
【问题描述】:
Kotlin 有一个 const 关键字。但我不认为 kotlin 中的常量是我认为的那样。它似乎与 C++ 中的 const 非常不同。在我看来,它仅适用于静态成员以及 Java 中的原语,并且不能为类变量编译:
data class User(val name: String, val id: Int)
fun getUser(): User { return User("Alex", 1) }
fun main(args: Array<String>) {
const val user = getUser() // does not compile
println("name = ${user.name}, id = ${user.id}")
// or
const val (name, id) = getUser() // does not compile either
println("name = $name, id = $id")
}
由于这似乎不起作用,我认为我真正想要的是第二类,它删除了我不想支持的操作:
class ConstUser : User
{
ConstUser(var name: String, val id: int) : base(name, id)
{ }
/// Somehow delte the setters here?
}
这种方法的明显缺点是我不能忘记更改这个类,以防我更改User,这对我来说看起来很危险。
但我不知道该怎么做。所以问题是:如何在 ideomatic Kotlin 中制作不可变对象?
【问题讨论】:
-
const与不变性无关。这是编译器在编译期间用原始值替换此类属性的使用的信号。不变性是通过不暴露变异访问器来实现的。比较 Kotlin 标准库中的Collection和MutableCollection接口
标签: kotlin constants immutability