Lists

Kotlin distinguishes between read-only and mutable lists.

The List interface represents immutable list of items. Don't confuse with Java List interface. To create instance you can use

  • any Java list classes such ArrayList
  • factory functions listOf() or List()

The MutableList interface represents mutable list of items. To create instance you can use

  • any Java list classes such ArrayList
  • factory functions mutableListOf() or MutableList()

You can use operator in instead the contains() method.

You can use operator [] instead the get()/set() methods.

Property size indicates current number of items in list.

var lst = listOf("1", "2", "3")
val mutableLst = mutableListOf("1","0","2")
val lst2 : List<String> = ArrayList()

if("1" in lst){/* ... */}

println (lst[1])
        
lst.forEach{
    println ("$it ")
}

class Cls{

    private val _lst = mutableListOf("1","0","2")

    // expose _lst to user as read-only list
    val lst : List<String>
        get() = _lst
}