简体   繁体   English

Java 记录与 Kotlin 数据类

[英]Java Records vs Kotlin Data Classes

Java 14 offers a new feature called Records , helping to create javabeans. Java 14 提供了一个名为Records的新功能,可帮助创建 javabean。

I've been using Kotlin for a couple of times, and of course, Java Records remind me Data Classes .我已经使用 Kotlin 好几次了,当然,Java Records 让我想起了Data Classes

Are they completely similar?它们完全相似吗? Or are there fundamental differences between them apart from the languages syntaxes?或者除了语言语法之外,它们之间是否存在根本差异?

This is a great article about all those differences. 这是一篇关于所有这些差异的好文章。

In summary:总之:

Similarities相似之处

  • generated methods: equals , hashCode , toString生成的方法: equalshashCodetoString
  • generated constructor生成的构造函数
  • generated getters (but Kotlin getter is called o.name , while Java uses o.name() )生成的 getter(但 Kotlin getter 被称为o.name ,而 Java 使用o.name()
  • can modify the canonical constructor可以修改规范构造函数
  • can add additional methods可以添加额外的方法

Differences差异

Kotlin's data classes support many other little things: Kotlin 的数据类支持许多其他小东西:

data class (Kotlin)数据类 (Kotlin) record (Java) 记录(Java)
copy method for easier object creation copy方法更容易创建对象 no copy methodcopy方法
variables can be var or val变量可以是varval variables can only be final变量只能是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.两者都非常适合减少代码膨胀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM