Get size of an array or a list in Kotlin
This article explores different ways to find the size of an array or a list in Kotlin.
1. Using size property
The standard solution to find the size of an array or a list in Kotlin is using its size property. This is demonstrated below for an Int Array and a List:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val array = IntArray(4) val array_size = array.size println(array_size) // 4 val list = listOf(1, 2, 3, 4, 5) val list_size = list.size println(list_size) // 5 } |
2. Using count() function
Another option to count the number of elements in the array or list is using the count() function with predicate as true. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val array = arrayOf(1, 2, 3) val array_size = array.count { true } println(array_size) // 3 val list = listOf("A", "B", "C", "D") val list_size = list.count { true } println(list_size) // 4 } |
3. Using Reflection
Although not recommended, we can dynamically access properties of an array using the java.lang.reflect.Array class. To get the length of an array, use the getLength() function. Note that this only works for an array, otherwise it will result in java.lang.IllegalArgumentException: Argument is not an array exception.
|
1 2 3 4 5 |
fun main() { val array = arrayOfNulls<Int>(5) val array_size = java.lang.reflect.Array.getLength(array) println(array_size) // 5 } |
That’s all about finding the size of an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)