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

问题描述 投票:0回答:2

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
,这对我来说看起来非常危险。

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

kotlin constants immutability
2个回答
9
投票

Kotlin 中的

const
修饰符用于 编译时常量。不变性是通过
val
关键字完成的。

Kotlin 有两种类型的属性:只读

val
和可变
var
val
相当于Java的
final
(不过我不知道这与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
属性的任何设置器,因为此类属性没有设置器。


0
投票

添加 jsamol 的答案:

  • 要更新不可变对象,可以使用 copy() 方法。
    -- 但要注意:它只是一个浅层副本,语义上就像 下面评论了行。
data class Car(
    val make: String,
    val manufactured: ZonedDateTime,
    val color: String
) {
    fun repaint(newColor: String): Car 
         = copy(color = newColor)

    //fun repaint(newColor: String): Car 
    //   = Car(make = this.make, manufactured = this.manufactured, color = newColor)
}
© www.soinside.com 2019 - 2024. All rights reserved.