Getting the Length of Kotlin Lists and Arrays

Introduces how to get the length, size, and total number of elements of List and Array.

Using size

Lists and arrays provide a size variable, and the length value is stored there.

As shown below, you can get the length of a list or array with the size variable.

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5)
    println("array size: ${array.size}")

    val list = listOf("a", "b", "c", "d", "e")
    println("list size: ${list.size}")
}

Output:

array size: 5
list size: 5

Using count()

Lists and arrays provide the count() function, which returns the number of elements.

As shown below, you can get the length of a list or array by using count().

fun main() {
    val array = arrayOf(1, 2, 3, 4, 5)
    println("array count: ${array.count()}")

    val list = listOf("a", "b", "c", "d", "e")
    println("list count: ${list.count()}")
}

Output:

array count: 5
list count: 5