在Java 14中向记录字段写入数据

huangapple go评论96阅读模式
英文:

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.

Source

Being immutable, at least shallowly, is precisely the point. Records are designed as value types, so no, you cannot change them.

huangapple
  • 本文由 发表于 2020年9月22日 07:05:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64001008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定