How to initialize List in Kotlin?

后端 未结 6 1772
清酒与你
清酒与你 2021-02-03 16:36

I see Kotlin has a List collection and I was wondering about different ways to initialize one. In Java, I could write:

List geeks = Ar         


        
6条回答
  •  眼角桃花
    2021-02-03 17:00

    Let me explain some use-cases : let's create an immutable(non changeable) list with initializing items :

    val myList = listOf("one" , "two" , "three")
    

    let's create a Mutable (changeable) list with initializing fields :

    val myList = mutableListOf("one" , "two" , "three")
    

    Let's declare an immutable(non changeable) and then instantiate it :

    lateinit var myList : List
    // and then in the code :
    myList = listOf("one" , "two" , "three")
    

    And finally add some extra items to each :

    val myList = listOf("one" , "two" , "three")
    myList.add() //Unresolved reference : add, no add method here as it is non mutable 
    
    val myMutableList = mutableListOf("one" , "two" , "three")
    myMutableList.add("four") // it's ok 
    

提交回复
热议问题