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

rtz*_*zui 7 constants immutability kotlin

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")
}
Run Code Online (Sandbox Code Playgroud)

由于这似乎不起作用,我认为我真正想要的是第二类,它删除我不想支持的操作:

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

这种方法的明显缺点是我不能忘记更改这个类,以防万一我更改了User,这对我来说看起来非常危险。

但我不知道该怎么做。所以问题是:如何在意识形态的 Kotlin 中创建不可变对象?

jsa*_*mol 9

Kotlin 中的修饰符const用于编译时常量。不变性是通过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
Run Code Online (Sandbox Code Playgroud)

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

  • 只读属性不一定是不可变的或最终的。只读属性可以保存可变对象: ```val list=mutableListOf(1,2,3) list.add(4) print(list)//[1,2,3,4]``` (2认同)