如何在 Kotlin 中创建不可变对象?

How to create immutable objects in Kotlin?

Kotlin 有一个常量关键字。但我不认为 kotlin 中的常量是我认为的那样。它似乎与 C++ 中的 const 非常不同。在我看来,它仅适用于静态成员和 Java 中的原语,并且不为 class-变量编译:

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,删除我不想支持的操作:

class ConstUser : User
{
    ConstUser(var name: String, val id: int) : base(name, id)
    { }
    /// Somehow delte the setters here?
}

这种方法的明显缺点是我不能忘记更改此 class,以防我更改 User,这对我来说看起来很危险。

但我不确定该怎么做。所以问题是:如何在 ideomatic Kotlin 中制作不可变对象?

Kotlin 中的 const 修饰符用于 compile-time constants。不变性是通过 val 关键字实现的。

Kotlin 有两种类型的属性:只读 val 和可变 varvals 等同于 Java 的 finals(不过我不知道这与 C++ 中的 const 有什么关系)并且这样声明的属性或变量可以'一旦设置就改变它们的值:

data class User(val name: String, val id: Int)

val user = User("Alex", 1)

user.name = "John" // won't compile, `val` cannot be reassigned
user = User("John", 2) // won't compile, `val` cannot be reassigned

您不必以某种方式隐藏或删除 val 属性的任何设置器,因为此类属性没有设置器。