英文:
Writing to a Record field in Java 14
问题
根据我对Java 14中Records的简要搜索,我了解到Record字段被编译为最终实例变量。这似乎意味着我不能写入Record字段... 教程中也没有提到关于写入Record字段的任何内容。
为什么会这样?为什么我不能像在C中使用struct一样在Java 14中使用Record?
感谢您提供的任何见解。
英文:
From a brief search on intro’s to Records in Java 14, I see that Record fields are compiled as final instance variables. This seems to imply I can’t write to Record fields.. none of the tutorials mention anything about writing to Record fields either.
Why is that? Why can’t I use a Record in Java 14 like I would use a struct in C?
Thanks for any insight
答案1
得分: 5
> 记录(Records)提供了一种紧凑的语法,用于声明作为浅不可变数据的透明容器的类。
>
> ...
>
> 记录的组件隐式地是 final 的。这种限制体现了一种默认情况下不可变的策略,适用于数据聚合。
至少在浅层上是不可变的,这正是关键所在。记录被设计为值类型,因此不,您不能更改它们。
英文:
> Records provide a compact syntax for declaring classes which are
> transparent holders for shallowly immutable data
>
> ...
>
> The components of a record are implicitly final. This restriction embodies an
> immutable by default policy that is widely applicable for data aggregates.
Being immutable, at least shallowly, is precisely the point. Records are designed as value types, so no, you cannot change them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论