How to copy an object in Kotlin

In C++ it is common to declare as well a copy constructor. This constructor is called whenever an object is newly created and directly assigne by another one. The following code demonstrates that.

auto obj1; // default constructor
auto obj2 = obj1; // copy constructor

In Kotlin things are a bit different. First of all Kotlin is working with pointers / references. The pointers will have a reference count. To demonstrate the behavior we will use the std::shared_ptr from the standard library.

var obj1 = AnyClass()
var obj2 = obj1;
auto obj1 = std::make_shared<AnyClass>();
auto obj2 = obj1;

If you use a data class, there will be the copy function which can be called to actually copy an object. For all other cases, you must implement a solution for yourself. To do that be carefull, because every (member) variable behaves like a shared_ptr.

In order to actually copy an object you have to implement your own solution.

class Point : Cloneable {
    var x = 0
    var y = 0

    public override fun clone(): Any {
        val newPoint = Point()
        newPoint.x = this.x
        newPoint.y = this.y
        return newPoint
    }
}

fun main() {
    var p = Point()
    var p2 = p.clone();
}