我以前用过C#,在那里我们可以定义一个struct
,它将是一个值类型.我现在正在学习Kotlin,据我所知,Kotlin data-class
通过价值进行比较,可以通过价值进行复制等.我在网上找到了一些关于这一点的讨论,但这并不简单,我想让精通C#和Kotlin的人来澄清这一点:我能把Kotlin的data class
解释成C#struct
并就此结束吗?如果没有,区别是什么?
我以前用过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 共有的一些限制是由不同的原因造成的:例如,数据类是最终的,因为来自数据类继承的自动生成函数的语义不明确.