Home > front end >  What is the difference between intArrayOf() and arrayOf()?
What is the difference between intArrayOf() and arrayOf()?

Time:01-30

In some sources I read that the first creates an array of elements of primitive type Int, and the second of packed Integer, in others that in Kotlin there are no primitive types, and it is the same. I haven't found any consensus, I'd be grateful if someone could explain.

Googled and read the book Kotlin in Actions

CodePudding user response:

arrayOf produce an object of class Array<T>. As you initialize array using this function, primitive values that you provide as arguments are being boxed. In other words, primitive integer value 1 will be converted to the object of type Int with value 1.

val array = arrayOf(1, 2, 3) // array's type is Array<Int>

intArrayOf is a function to create object of type IntArray. This class does not have boxing overhead. Therefore values that you provide are not being boxed.

val array = intArrayOf(1, 2, 3) // array's type is IntArray

Note that both classes IntArray and Array<T> have no inheritance relation. But they contain same set of methods and properties.

IntArray represents primitive type arrays, which are designed specifically to prevent deriving array type from provided elements and avoid boxing overhead.

However, if you are calling get method on IntArray, you will get value of type Int, same as when you call get on Array<Int>.

CodePudding user response:

intArrayOf() and arrayOf() are both functions in Kotlin for creating arrays. The main difference between the two functions is the type of elements that the resulting arrays can hold.

intArrayOf() is used to create an array of primitive Int values, while arrayOf() is used to create an array of objects, such as String, Float, or other object types.

Here's an example of using intArrayOf():

val intArray = intArrayOf(1, 2, 3, 4, 5)

And here's an example of using arrayOf():

val stringArray = arrayOf("A", "B", "C")

Note that while intArrayOf() creates an array of primitive Int values, arrayOf() creates an array of Int objects, which are reference types. This means that the elements in the array created by arrayOf() are objects that can have different values, while the elements in the array created by intArrayOf() are primitive values that cannot have different values.

  • Related