Kotlin's data class == C#'s 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.

Some limitations that the data classes have in common with structs are caused by a different reason: for example, data classes are final because of unclear semantics of the auto-generated functions that would come from data class inheritance.


Structs in C# can always be created without parameters even if they have a constructor, while data classes in Kotlin requires a parameterized constructor.

To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:

  • The primary constructor needs to have at least one parameter;

...

https://kotlinlang.org/docs/reference/data-classes.html

Tags:

C#

Kotlin