LoginSignup
2
1

More than 5 years have passed since last update.

val mutableList vs var List

Last updated at Posted at 2018-08-30

どう違うのか?
試してみましょう


    val items1 = mutableListOf(1,2,3)
    println(items1.toString())  // [1, 2, 3]
    items1 = mutableListOf(10)  // Error:(9, 4) Val cannot be reassigned
    items1.add(4)
    println(items1.toString())  // [1, 2, 3, 4]

    var items2 = listOf(1,2,3)
    items2.add(4)               // Error:(10, 11) Unresolved reference: add
    println(items2.toString())  // [1, 2, 3]
    items2 = listOf(11)
    println(items2.toString())  // [11]

varは最代入可能な通常の変数、valはfinalに置き換わるので再代入が不可能な変数。mutableListは普通のListになるのでaddが可能、Listはイミュータブル扱いになるので、addはできない。
というふうに整理できるのですね

2
1
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
2
1