kotlin list

List in Kotlin

Creation of list by these functions in kotlin:

arrayListOf

emptyList

listOf

listOfNotNull

mutableListOf

Function Type
  arrayListOf   ArrayList<T>
emptyList List<T>
  listOf   List<T>
listOfNotNull List<T>
  mutableListOf   MutableList<T>

Examples:

val list = listOf(3,5,7) val list = arrayListOf(3,5,7) val list = mutableListOf(“hi”, “hello”, “hola”)  
  // empty lists val list = listOf<Int>() val list = arrayListOf<Double>() val list = mutableListOf<String>() val list: List<Int> = emptyList()
// nullability (implicit or explicit) val list = listOf(“hi”, null)     // [a, null]
val list: List<String?> = listOf(“hi”, null) // [a, null]
  val list = arrayListOf(“hi”, null)   // [a, null]
val list = mutableListOf(“hi”, null) // [a, null]
val list = listOfNotNull<String>(“hi”, null) // [a]
val list = listOfNotNull(“hi”, null) // [a]
// comparison: listOf vs listOfNotNull val list = listOf(“hi”, null)     // [a, null]
val list = listOfNotNull(“hi”, null) //

The difference between listOf and listOfNotNull :

  listOf : Returns an immutable list containing only the specified object element.

  listOfNotNull : Returns a new read-only list either of single given element, if it is not null, or empty list if the element is null.

List casting in kotlin

Examples:

val a: List<Int> = listOf(3,5,7)

val b: Collection<Int> = listOf(3,5,7)

val c: Iterable<Int> = listOf(3,5,7)

val a: MutableList<Int>    = mutableListOf(3,5,7)

val b: List<Int>         = mutableListOf(3,5,7)

val c: MutableCollection<Int> = mutableListOf(3,5,7)

val d: Collection<Int>     = mutableListOf(3,5,7)

val e: Iterable<Int>   = mutableListOf(3,5,7)

val f: MutableIterable<Int>   = mutableListOf(3,5,7)

val a: ArrayList<Int> = arrayListOf(3,5,7)

val b: AbstractList<Int> = arrayListOf(3,5,7)

val c: MutableList<Int> = arrayListOf(3,5,7)

val d: AbstractCollection<Int> = arrayListOf(3,5,7)

val e: MutableCollection<Int> = arrayListOf(3,5,7)

val f: Collection<Int>     = arrayListOf(3,5,7)

val g: MutableIterable<Int> = arrayListOf(3,5,7)

val h: Iterable<Int>       = arrayListOf(3,5,7)

Leave a Reply

Your email address will not be published. Required fields are marked *