Java Records vs. Kotlin Data Classes

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

Java Records vs Kotlin Data Classes

问题

Java 14提供了一个名为Records的新功能,有助于创建JavaBean。

我之前使用过Kotlin几次,当然,Java Records让我想起了Data Classes

它们完全相似吗?除了语言语法之外,它们之间是否存在根本性的区别?

英文:

Java 14 offers a new feature called Records, helping to create javabeans.

I've been using Kotlin for a couple of times, and of course, Java Records remind me Data Classes.

Are they completely similar? Or are there fundamental differences between them apart from the languages syntaxes?

答案1

得分: 21

以下是翻译好的部分:

这是一篇关于所有这些差异的精彩文章。

总结:

相似之处

  • 自动生成的方法:equalshashCodetoString
  • 自动生成的构造函数
  • 自动生成的获取器(但是 Kotlin 的获取器称为 o.name,而 Java 使用 o.name()
  • 可以修改规范构造函数
  • 可以添加额外的方法

差异之处

Kotlin 的数据类支持许多其他小功能:

数据类(Kotlin) 记录类(Java)
用于更轻松地创建对象的 copy 方法 没有 copy 方法
变量可以是 varval 变量只能是 final
可以继承其他非数据类 无法继承
可以定义非构造函数可变变量 只能定义静态变量

两者都非常适用于减少代码膨胀。

英文:

This is a great article about all those differences.

In summary:

Similarities

  • generated methods: equals, hashCode, toString
  • generated constructor
  • generated getters (but Kotlin getter is called o.name, while Java uses o.name())
  • can modify the canonical constructor
  • can add additional methods

Differences

Kotlin's data classes support many other little things:

data class (Kotlin) record (Java)
copy method for easier object creation no copy method
variables can be var or val variables can only be final
can inherit from other non-data classes no inheritance
can define non-constructor mutable variables can define only static variables

Both are great for reducing the code bloat.

huangapple
  • 本文由 发表于 2020年10月22日 00:55:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64468267.html
匿名

发表评论

匿名网友

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

确定