Avatar ·

How to clone an object in Kotlin? Problem with mutability and references

Hello everyone! I just started learning Kotlin and encountered a problem with cloning objects. In Java I used the `clone()` method from the `Cloneable` interface, but in Kotlin it seems everything works differently.\n\nI have a simple data class `User`:\n\n```kotlin\ndata class User(val name: String, var age: Int, val hobbies: MutableList)\n```\n\nI create an object and want to make a full copy of it so that changes in the copy don't affect the original. But when I simply assign one object to another, it creates a new reference, not a copy:\n\n```kotlin\nval user1 = User("Alice", 25, mutableListOf("reading", "swimming"))\nval user2 = user1 // This is not a copy, but a reference!\n\nuser2.age = 30\nprintln(user1.age) // Prints 30, but should be 25! Changes affected the original.\n```\n\nI tried using `copy()`