I’m porting a 2D graphics engine from Swift to Kotlin. Large parts of the data model are nested structs in Swift. As a simple example:
struct Point {
var x: Float
var y: Float
}
struct Size {
var width: Float
var height: Float
}
struct Rect {
var origin: Point
var size: Size
}
Many model structures are deeply nested, with way more levels than here. Also, as we use struct
s instead of class
es for most types, which are value typed in Swift, we can easily use pure functions for 2D operations, like in this small, contrived example:
func translate(rect1: Rect, dx: Float) -> Rect {
var rect2 = rect1 // Creates a mutable deep copy
rect2.origin.x += dx
return rect2
}
This approach gives us a high performance, no memory handling issues (everything lives on the stack), and great testability. As the struct
s are value typed, we cannot accidentally create shallow copies and modify the wrong objects.
What’s the idiomatic way to create such a model in Kotlin?
It looks like Kotlin’s data classes are a solution, but I don’t know how copying deeply nested data classes is usually done. Do you create custom deepCopy() methods everywhere?
Should I be worried about the performance if the call of a copy()/deepCopy() method triggers a torrent of other copy()/deepCopy() calls down the model? (From a C programmer’s perspective, I see thousands of small, short lived allocations on the heap)