

If you need to create an Array, the simplest way is using the arrayOfNulls function of the standard library: val notActualPeople: Array = arrayOfNulls(13)Ģ. Use Array when you’re forced to use the Array class by an API, or if you need to store potentially null values, which an Array is of course able to do. Here’s an example of this, using their constructors: val intArray = IntArray(10)

They are also easier to create - an Array requires a non-null value for each of its indexes, while IntArray initializes them automatically to 0 values. Primitive arrays are more performant, as they don’t require boxing for every element. These can be created with their own (also non-generic, like the class itself) intArrayOf factory method: val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) (There are similarly named classes for the other primitive types as well, such as ByteArray, CharArray, etc.) IntArray is a special class that lets you use a primitive array instead, i.e. This is what you get when you use the generic arrayOf method to create an array: val arrayOfInts: Array = arrayOf(1, 2, 3, 4, 5) When using this with the Int type parameter, what you end up in the bytecode is an Integer instance, in Java parlance. Array vs IntArray What’s the difference between Array and IntArray?Īrray uses the generic Array class, which can store a fixed number of elements for any T type. The best way I found is to have a look at some of the most frequently asked questions about Kotlin on StackOverflow. I am currently defending the third place on the top users list of the Kotlin tag on StackOverflow, and I wanted to make use of the bragging rights this gives me while I can. When you’re done with this one, read the second and third parts as well! This is the written version of a talk I gave recently, and since it was quite long, this is the first of three articles about it.
