
It was introduced to overcome the shortcomings of traditional wrappers around some types. Instances of data classes are written to the heap.Īre there any other options? There is another option which is Inline class (available since Kotlin 1.3). Primitive values can be written to the stack which is fast and efficient. To adopt this immutability pattern in Swift, you’ll have to write quite a lot of boilerplate code.īut there is a downside of using data class. In fact, Swift’s struct isn’t quite as convenient as Kotlin’s data class because Swift’s struct doesn’t have a similar “copy” function. If we need to overwrite existing field values in one of our immutable objects, we use the data class’s “copy” function to set a new value for the desired field while preserving the rest of the values. First an example of Swift struct: struct Person ") // Person2 age: 30ĭata class is indeed displaying the expected result! We use data class to create immutable objects. On the other hand, struct is a value type.

Both struct and data class are simplified versions of a class.

It works fine but it is not a perfect solution. Until recently I have used data class in Kotlin whenever I need to convert a Swift struct into a Kotlin equivalent in Android project. What is the best possible equivalent of Swift Struct in Kotlin?
