0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinのシャローコピーとディープコピー

Posted at

Kotlinでオブジェクトをコピーする時にシャローコピーとディープコピーの2つの違いがある。コピー元の変数に影響を与えない方法をメモします。

シャローコピー

シャローコピーはオブジェクトを新しいインスタンスとして作られるけど、内部のプロパティは元のオブジェクトと共有されます。なのでu2で変更したリストはu1にも反映されます。

data class User(val name: String, val items: MutableList<String>)

val u1 = User("John", mutableListOf("A", "B"))
val u2 = u1
u2.items.add("C")

println(u1) // User(name=John, items=[A, B, C])

ディープコピー

ディープコピーはオブジェクトと内部の参照型プロパティも新しいインスタンスとしてコピーします。なので、元のオブジェクトとコピー後のオブジェクトがそれぞれ独立しています。
toMutableList() を使ってリストのコピーを作ることで、元のオブジェクトと完全に独立した状態にできます。

data class User(val name: String, val items: MutableList<String>) {
    fun deepCopy(): User {
        return User(name, items.toMutableList())
    }
}

val u1 = User("Taro", mutableListOf("A", "B"))
val u2 = u1.deepCopy()

u2.items.add("C")

println(u1) // User(name=Taro, items=[A, B])
println(u2) // User(name=Taro, items=[A, B, C])
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?