Foggy day

Kotlin - collection about immutable, mutable 본문

Kotlin

Kotlin - collection about immutable, mutable

jinhan38 2021. 3. 16. 22:01

 

In Kotlin, there are two types immutable and mutable.

 

 

The first is the immutable list. If you use +(plus) operator, plus value would be added to the list.

The important thing is the fact that +(plus) operator create a new list.

class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)

        val data1 = listOf(3, 4, 5, 6)
        val data2 = data1 + 7
        val data3 = data1 + data2

        println(data1)
        println(data2)
        println(data3)

        val strData1 = listOf<String>("a", "b", "c")
        val strData2 = strData1 + "d"
        val strData3 = strData1 + strData2

        println(strData1)
        println(strData2)
        println(strData3)
    }

}

 

 

 

 

 

 

The second is the mutable list.

Type of data2, data3, strData2, and strData3 is Boolean.

class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)


        val data1 = mutableListOf(3, 4, 5)
        val data2 = data1.add(6)
        val data3 = data1.addAll(data1)

        println(data1)
        println(data2)
        println(data3)

        val strData1 = mutableListOf("a", "b", "c")
        val strData2  = strData1.add("d")
        val strData3 = strData1.addAll(strData1)

        println(strData1)
        println(strData2)
        println(strData3)
    }

}

 

 

 

'Kotlin' 카테고리의 다른 글

Kotlin - extension function, fold, reduce  (0) 2021.03.17
Kotlin - function, expression syntax  (0) 2021.03.16
Kotlin - Singleton  (0) 2021.03.16
Kotlin - companion object  (0) 2021.03.16
Kotlin - destructing  (0) 2021.03.16