【问题标题】:How to create immutable objects in Kotlin?如何在 Kotlin 中创建不可变对象?
【发布时间】: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 标准库中的 CollectionMutableCollection 接口

标签: kotlin constants immutability


【解决方案1】:

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 属性的任何设置器,因为此类属性没有设置器。

【讨论】:

  • 只读属性不一定是不可变的,也不一定是最终的。只读属性可以保存可变对象:val list=mutableListOf(1,2,3) list.add(4) print(list)//[1,2,3,4]
猜你喜欢
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 2021-08-13
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多