我以前用过C#,在那里我们可以定义一个struct,它将是一个值类型.我现在正在学习Kotlin,据我所知,Kotlin data-class通过价值进行比较,可以通过价值进行复制等.我在网上找到了一些关于这一点的讨论,但这并不简单,我想让精通C#和Kotlin的人来澄清这一点:我能把Kotlin的data class解释成C#struct并就此结束吗?如果没有,区别是什么?

推荐答案

The main difference between Kotlin data classes and C# structs is that the Kotlin data classes are still classes, they are passed by reference (a referential type, speaking in terms of C#) and stored in the same heap with other objects (not taking possible JVM optimizations into account) instead of the stack, in the same form as the other objects.

The copy and equality check implementations for data classes are just generated into the methods of the class and are called as instance methods in a JVM-natural way.

数据类与 struct 共有的一些限制是由不同的原因造成的:例如,数据类是最终的,因为来自数据类继承的自动生成函数的语义不明确.

Kotlin相关问答推荐

如何编写带有依赖项的自定义Kotlin串行化程序?

关键字';在When Kotlin When-语句中

如何避免使用公共类实现内部接口

用vararg替换列表的设计弃用警告

为什么不';Kotlin是否在数据类构造函数中隐式分配null值可为null的字段?

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

Kotlin 中命名构造函数的惯用方式

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

如何避免键盘打开时jetpack compose 内容上升

如何在 kotlin 中创建自定义迭代器并添加到现有类?

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

Kotlin 枚举中的循环引用

是否可以在 kotlin 中嵌套数据类?

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

runOnUiThread 没有调用

Kotlin的BiMap/2-way hashmap

我们如何在Java注释声明中引用Kotlin常量?

如何序列化/反序列化Kotlin密封类?

Kotlin 警告:Conditional branch result of type ... is implicity cast of Any?

你如何在 Kotlin 中注释 Pair 参数?